Reputation: 5789
Im working on an MVC application and for my current form I have a ViewModel like
public class MyViewModel
{
public MyModel MyModel { get; set; }
...
and MyModel has a type
public class MyModel
{
public int MyModelTypeId { get; set; }
...
Now, i need a DropDownList to popuulate MyModelTypeId,
this is what I Have in the View:
@Html.DropDownList("MyModelTypeId", String.Empty)
and in the Controller:
ViewBag.MyModelTypeId = new SelectList(db.MyModelTypes, "MyModelTypeId", "MyModelTypeName", model.MyModel.MyModelTypeId);
Now, the drop down is being populated well but, on post, the picked value is not being binded to 'MyModel'
What am I doing wrong
Upvotes: 2
Views: 615
Reputation: 4320
The dropdown list is being bound to the MyModelTypeId
property you have created in the ViewBag, not the MyModelTypeId
property of the `MyModel' class.
You should store the select list in MyModel
public class MyModel
{
public int MyModelTypeId { get; set; }
public IEnumerable<SelectListItem> MyModelTypes { get; set; }
Assign the select list you create in your controller to this property, and then render the dropdown list in your view, passing the MyModelTypeId
as the value to bind the selected item to, and MyModelTypes
as the select list to use:
@Html.DropDownListFor(m => m.MyModel.MyModelTypeId, Model.MyModel.MyModelTypes)
When the form is submitted, the selected value will be bound to MyModel.MyModelTypeId
Upvotes: 2