MVC5 - How to set "selectedValue" in DropDownListFor Html helper

Dino picture Dino · Jan 18, 2017 · Viewed 25.1k times · Source

As the question says: How to set selectedValue in DropDownListFor Html helper?

Tried most of the other solutions but none worked that's why I am opening a new question.

Nothing of these helped:

@Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2), htmlAttributes: new { @class = "form-control" })

//Not working with or without cast
@Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Single(x => x.Id == 2)), htmlAttributes: new { @class = "form-control" })
@Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Where(x => x.Id == 2).FirstOrDefault()), htmlAttributes: new { @class = "form-control" })

@Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", new SelectListItem() { Value="2", Selected=true}), htmlAttributes: new { @class = "form-control" })

I would like to avoid manual creation of SelectListItems or a ViewModel just for the list if possible.

Answer

user3559349 picture user3559349 · Jan 19, 2017

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" })