Select doesn\'t work for me with DropDownListFor. Can anyone help me?
I have musiccategories and artists that belong to one musiccategory. On my page I want to show
DropDownListFor, selected = true doesn't work
Yup.
But I can't make one specified option in the drop down list selected, the first option is always selected at first.
When you use
// I don't recommend using the variable `model` for the lambda
Html.DropDownListFor(m => m., > ...
MVC Ignores .selected and instead verifies the m. value against the values in .
public class DropDownModel
{
public int ID3 { get; set; }
public int ID4 { get; set; }
public int ID5 { get; set; }
public IEnumerable Items { get; set; }
}
public ActionResult Index()
{
var model = new DropDownModel
{
ID3 = 3, // Third
ID4 = 4, // Second
ID5 = 5, // There is no "5" so defaults to "First"
Items = new List
{
new SelectListItem { Text = "First (Default)", Value = "1" },
new SelectListItem { Text = "Second (Selected)", Value = "2", Selected = true },
new SelectListItem { Text = "Third", Value = "3" },
new SelectListItem { Text = "Forth", Value = "4" },
}
};
return View(model);
}
@Html.DropDownListFor(m => m.ID3, Model.Items)
@Html.DropDownListFor(m => m.ID4, Model.Items)
@Html.DropDownListFor(m => m.ID5, Model.Items)
Result:
dotnetfiddle.net Example