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" })
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…