Search code examples
c#asp.netasp.net-mvcasp.net-mvc-5

Getting selected value from dropdown when editing aggregated object at MVC 5.0


I can't get the value from DropDownList when the DropDownList targets a field of an object inside the Model.

@Html.DropDownList("MyID", null, htmlAttributes: new { @class = "form-control" })

The ViewBag is filled with this:

ViewBag.MyID = new SelectList(db.WFMasters, "MyID", "Code", wFDefDetail.wfDef.MyID); //MyID is property of wfDef. Model is wFDefDetail.

I have no trouble to get the value of the DropDownList if the target value is a property of the model.

In this case, the DropDownList is correctly filled but I don't get the selected value at the View Controller method. The controller receives null for wFDefDetail.wfDef.MyID.

Also, if I change to @html.EditorFor method I can get the value of wFDefDetail.wfDef.MyID so must be some detail I miss to put DropDownList to work too.


Solution

  • To map data properly dropdown name property should match the model like below:

    @Html.DropDownList("wfDef.MyID", (IEnumerable<SelectListItem>)ViewBag.MyID, htmlAttributes: new { @class = "form-control" })