MVC5 – How to set “selectedValue” in DropDownListFor Html helper

When you use the DropDownListFor() (or DropDownList()) method to bind to a model property, its the value of the property that sets the selected option.

Internally, the methods generate their own IEnumerable<SelectListItem> and set the Selected property based on the value of the property, and therefore setting the Selected property in your code is ignored. The only time its respected is when you do not bind to a model property, for example using

@Html.DropDownList("NotAModelProperty", new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2))

Note your can inspect the source code, in particular the SelectInternal() and GetSelectListWithDefaultValue() methods to see how it works in detail.

To display the selected option when the view is first rendered, set the value of the property in the GET method before you pass the model to the view

I also recommend your view model contains a property IEnumerable<SelectListItem> TipoviDepozita and that you generate the SelectList in the controller

var model = new YourModel()
{
    TipoviDepozita = new SelectList(yourCollection, "Id", "Naziv"),
    TipPopustaId = 2 // set the selected option
}
return View(model);

so the view becomes

@Html.DropDownListFor(m => m.TipPopustaId, Model.TipoviDepozita, new { @class = "form-control" })

Leave a Comment