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.
DropDownListFor()
sets the selected option based on the value of propertyTipPopustaId
(that is bhow model binding works). Set its value in the controller before you pass the model to the view and the correct option will be selected (setting theSelected
property is ignored when binding to a model property) – Intramuscular