I have created a sample MVC3 application for BookShop. I have a create action. In the create action users enter name of a book, author name and select a genre name. It is working without errors. But in the controller, I am not getting the selected genre name ( - the genre object comes as null). How do we correct it?
Note: When I write @Html.DropDownList("GenreId", String.Empty)
the Model Binding capabilities built into ASP.NET MVC, will attempt to populate an object of that type using form inputs. E.g. it will try to set the book object’s GenreId value. But Book does not contain the property GenreId. However the dropdown can show the values by reading required values from ViewBag.
CODE
@model MyBookShopApp.Book
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>BOOK</legend>
<div >
@Html.LabelFor(model => model.Title) :~: @Html.EditorFor(model => model.Title)
</div>
<div >
@Html.LabelFor(model => model.Artist.Name ) :*: @Html.EditorFor(model => model.Artist.Name)
</div>
<div >
@Html.LabelFor(model => model.GenreEntity.Name, "The Genre") :: @Html.DropDownList("GenreId", String.Empty)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
CONTROLLER
namespace MyBookShopApp.Controllers
{
public class StoreManagerController : Controller
{
List<GenreEntity> listOfGenres = new List<GenreEntity>()
{
new GenreEntity { Name = "Fiction", GenreId = 1 },
new GenreEntity { Name = "Science", GenreId = 2 },
new GenreEntity { Name = "Religious", GenreId = 3 },
};
List<Book> bookList = new List<Book>()
{
new Book
{
BookId = 1,Title = "Book1",
GenreEntity = new GenreEntity { Name = "Fiction", GenreId = 1 },
Artist = new Artist { ArtistId = 1, Name = "Dinesh" }
},
new Book
{
BookId = 2,Title = "Book2",
GenreEntity = new GenreEntity { Name = "Science", GenreId = 2 },
Artist = new Artist { ArtistId = 1, Name = "Lijo" }
},
new Book
{
BookId = 3,Title = "Book3",
GenreEntity = new GenreEntity { Name = "Religious", GenreId = 3 },
Artist = new Artist { ArtistId = 1, Name = "Santhosh" }
}
};
#region CREATE
// GET:
public ActionResult Create()
{
ViewBag.GenreId = new SelectList(listOfGenres, "GenreId", "Name");
return View();
}
// POST:
[HttpPost]
public ActionResult Create(Book theBook)
{
if (ModelState.IsValid)
{
//Save the book in DB first and then redirectToAction.
return RedirectToAction("Index");
}
return View(theBook);
}
#endregion
}
}
Book Class
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public GenreEntity GenreEntity { get; set; }
public Artist Artist { get; set; }
}
GenreEntity
public class GenreEntity
{
public string Name { get; set; }
public int GenreId { get; set; }
}
Artist Class
public class Artist
{
public int ArtistId { get; set; }
public string Name { get; set; }
}
REFERENCE: