Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

People also ask

What is HTML DropDownList?

DropDownList(String, String, IEnumerable<SelectListItem>, Object, Object) Returns an HTML drop-down list control that has the specified name, custom attributes defined by an attribute object, and default selection, and that contains the specified list items and default item.

What is DropDownListFor?

DropDownListFor will automatically select the selected value by using the specified property: // Will select the item in model. Equipments that matches Model. EquipmentId @Html.


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.