ASP.NET MVC3: Object from DropdownList in Null in Controller

为君一笑 提交于 2019-12-04 18:45:54

@Html.DropDownList("GenreId", String.Empty) creates a SELECT with the name GenreId. However MVC3 is expecting the name GenreEntity.Name to bind to Book.

The simple solution is to modify public ActionResult Create(Book theBook) to public ActionResult Create(Book theBook, string genreId) to receive the genreId that got posted back

Alternatively

@Html.LabelFor(model => model.GenreEntity.GenreId, "The Genre")
@Html.DropDownListFor(model => model.GenreEntity.GenreId, (SelectList)ViewBag.GenreId, String.Empty)

Remember to set your ViewBag inside the HttpPost Create method also.

Edit Corrected the property name from BookId to GenreId

Your DropDown is trying to assign its value to a property called Book.GenreId. Your GenreEntity class has the GenreId property, not Book (based on the code you pasted above).

You can correct this by modifying the dropdown to this:

@Html.DropDownList("GenreEntity.GenreId", String.Empty)

This will tell MVC to assign the value of the drop down to Book.GenreEntity.GenreId.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!