asp.net-core-mvcdropdownlistfor

How can I set the value of a Html.DropDownList in ASP.NET Core MVC


I am working on an edit form and I am unable to set the value shown in an Html.DropDownList based on the model value.

This is what I have so far:

@Html.DropDownList("OrgId", 
                   (IEnumerable<SelectListItem>)ViewBag.orgList, 
                   Model.ShortName, 
                   new { @class = "form-select", @style="width:120px"})

When the form loads it does have the correct ShortName corresponding to the model, but when the form is submitted the index associated with the ShortName is 0 instead of the Id. It is just adding the ShortName at the top of the list and not setting it to the correct index in the list.

In the controller ViewBag.orgList is being set thus:

ViewBag.orgList = new SelectList(_context.Organizations
                                         .Where(x => x.Id != 0)
                                         .OrderBy(p => p.ShortName), 
                                 "Id", "ShortName");

Maybe I should be using DropDownListFor but I am new to ASP.NET Core MVC and don't know which is the best option.

Can someone please point me in the right direction?


Solution

  • Found a solution although it feels a bit hacky:

    @Html.DropDownList("ShortName", (IEnumerable<SelectListItem>)ViewBag.orgList, Model.ShortName, new { @class = "form-select", @id="ShortName"})
    

    This then allows you to pass a string ShortName to a controller Action method. Works!!