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

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

I tried most of the other solutions, but no one worked, so I open a new question.

None of this 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 manually creating SelectListItems or ViewModel for a list only, if possible.

+8
asp.net-mvc asp.net-mvc-5 html-helper
source share
2 answers

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

Internally, the methods generate their own IEnumerable<SelectListItem> and set the Selected property based on the value of the property, so setting the Selected property in your code is ignored. The only time you respect him is when you don’t get attached to the property of the model, for example, using

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

Please note that you can check the source code , in particular the SelectInternal() and GetSelectListWithDefaultValue() methods, to see how it works in detail.

To display the selected option the first time you render the view, set the property value in the GET method before passing the model to the view

I also recommend that your view model contain the IEnumerable<SelectListItem> TipoviDepozita and that you generate a 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" }) 
+9
source share

I am sure that your return value of the choice is a string, not an int, when you declare it in your model.

Example:

 public class MyModel { public string TipPopustaId { get; set; } } 
0
source share

All Articles