I have this annoying problem where my DropDownlist doesn\'t select the current value by default.
Controller:
var YearsCycling = new SelectList(new Li
I'm sure you're way past this, but I just got burned on this a moment ago because I had named the dropdown list the same name as the property in my view model class.
Changing the dropdown list name to something else cured it right up.
Binding dropdownlist is very tricky in MVC it embarrassed me a lot you can do it with this in your controller get all your cities list put it in viewBag
Create
ViewBag.CityId = new SelectList(db.Cities, "ID", "Name");
user.CityID if you are in Edit so that on edit it select the city
ViewBag.CityId = new SelectList(db.Cities, "ID", "Name", user.CityID);
in your View just do this trick
@Html.DropDownList("CityId", "Select")
this is the most simplest way I know....
Your code should be.
var YearsCycling = 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", Selected=true},
new SelectListItem(){ Value="10+yrs", Text="10+yrs"}
};
ViewBag.YearsCycling = YearsCycling;
You could use this overload instead.
<%:Html.DropDownListFor(model=>model.YearsCycling,ViewBag.YearsCycling as List<SelectListItem>) %>
If you are rendering your list like this: @Html.DropDownListFor(model => model.EntityID, Model.EntitySelectList)
The value .NET MVC will use when rendering the select options will match the value of model.EntityID.ToString()
.
... It will not select the Model.EntitySelectList.SelectedValue
... Or any of the EntitySelectList.Item.SelectedValue
items.
... In other words, when rendering a DropDownListFor something other than the list itself, the SelectedValue properties of both the List and the List Items are ignored.
No matter what Model.EntitySelectList.SelectedValue or Model.EntitySelectList.Item.SelectedValue is set, ASP.NET MVC will not render selection. Use the model.EntityID
instead.
I have some problems when using a ViewBag with the same name as the html-element.
So, doesn't use a DropDownList for EventId, when the SelectList is stored in a ViewBag.EventId.
Change ViewBag.EventId to ViewBag.EventData, and it's fixed.
Just ensure that the variable name set on ViewBag is different to the name assigned to the dropdownlist - i.e. don't do:
Controller:
ViewBag.CityId = new SelectList(....)
View:
@Html.DropDownList("CityId", ...
Just use a different viewbag variable name.
I've had problems when using the same ViewBag variable name as a html control name with drop down lists and listboxes.