I have this annoying problem where my DropDownlist doesn\'t select the current value by default.
Controller:
var YearsCycling = new SelectList(new Li
Try this:
Create a viewmodel:
public class MyViewModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> YearsCycling { get; set; }
}
Controller:
var YearsCycling = new SelectList(new List<SelectListItem>()
{
new SelectListItem(){ Value="1yr", Text="1yr"},
new SelectListItem(){ Value="1-3yrs", Text="1-3yrs"},
new SelectListItem(){ Value="3-5yrs", Text="3-5yrs"},
new SelectListItem(){ Value="5-10yrs", Text="5-10yrs"},
new SelectListItem(){ Value="10+yrs", Text="10+yrs"}
},
"Value",
"Text");
MyViewModel model = new MyViewModel();
model.YearsCycling = YearsCycling;
model.SelectedValue = "5-10yrs";
return View(model);
View:
<%:Html.DropDownListFor(model=>model.SelectedValue,(SelectList)Model.YearsCycling) %>
Also Html.DropDownListFor uses values from POST request.
Therefore if you have the same parameter in POST data MVC will use it even if you have different value in model.
Check if you have the same name in request and change it.