Why is my default value for DropDownListFor not working properly?
asp.net-mvc-5, html.dropdownlistfor
Solution
Try this:
In your ViewModel, add an integer to store the selected domain id:
public int SelectedDomainId { get; set; }
Change your DropDownListFor to:
@Html.DropDownListFor(model => model.SelectedDomainId,
new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
new { @class = "form-control" })
Now on your post-back the selected id will be posted in SelectedDomainId.
Or, you could add the single domain object to your VM (to indicate which one was selected):
public Domain SelectedDomain { get; set; }
And change your DropDownListFor to:
@Html.DropDownListFor(model => model.SelectedDomain,
new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
new { @class = "form-control" })
I usually use the selected ID, but I think either should work
Here is another good example:
MVC3 DropDownListFor - a simple example?
Problem
For whatever reason, my default value for my Html.DropDownListFor isn't working: ``` @Html.DropDownListFor(model => model.DomainList, new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId), new { @class = "form-control" }) ``` Any idea why? UPDATE With the answer below, I updated my code to the following: ``` @Html.DropDownListFor(model => model.SelectedDomain, new SelectList(Model.DomainList, "DomainId", "Name", Model.SelectedDomain), "Select a Domain", new { @class = "form-control" }) ```