Asp.net MVC, Html.DropDownList and Selected Value
I recently ran into the altogether common problem of the Html.DropDownList helper rendering a drop down list with no value selected. This is a major problem when editing data as by default, the first value is selected and saving would mean the first value is used.
There have been a few issues resulting in the same error. My issue was that I was setting the Name of the drop down list to be equal to the property on my model. I was using the Entity Framework, and had an Image class with a navigation property called Category. I was using this to render the ddl:
<%= Html.DropDownList("Category", (IEnumerable<SelectListItem>)ViewData["categories"])%>
In my controller, I was setting the ViewData like this:
this.ViewData["categories"] = new SelectList(db.CategorySet.ToList(), "CategoryId", "Title", img.CategoryReference.EntityKey);
Unfortunately, even though I had set the selected value (third parameter to the SelectList constructor), the ddl had no value selected.
The fix was quite simple:
<%= Html.DropDownList("CategoryId", (IEnumerable<SelectListItem>)ViewData["categories"])%>
I just changed the Name of the drop down and handled the assignment in the controller.
The reason behind this problem is that asp.net MVC first looks for a match between the name of the drop down and a property on the model. If there’s a match, the selected value of the SelectList is overridden. Changing the name of the drop down is all it takes to remedy the issue.
Hope that helps.
10 Comments
Martin Evans said
Thanks very much. This seems to be the only example any where on the internet where the viewdata is cast to IEnumerable<SelectListItem> in the markup!
http:// said
Can you show the related code? i.e., CategorySet, CategoryReference, the controller method code?
HeartattacK said
Sorry for the delay in getting back to this..I was setting up my new apartment, and it took a LOT of work.
The related code is very simple.
img is an Image (not System.Drawing.Image, just an Entity).
Each image has a Category. Each category can have one or mor Images.
I'm using The Entity Framework, and CategorySet is the plural of Category.
-------------------
The controller to handle the postback is like this:
public ActionResult Edit(string ImageId, string Description, int Rating, string CategoryId)
{
Guid imageId = new Guid(ImageId);
var img = db.ImageSet.Where(x => x.ImageId == imageId).First();
try
{
img.Description = Description;
img.Rating = Rating;
img.CategoryReference.EntityKey = new System.Data.EntityKey("StudiomorphEntities.CategorySet",
"CategoryId", new Guid(CategoryId));
.......
db.SaveChanges();
Matt said
I was experiencing a similar problem but I was eventually able to get the selected value to show without matching the name of the dropdown to a property of the select list.
HTML -
<% =Html.DropDownList("PropertyStyleId", (SelectList)ViewData["PropertyStyles"], "(Select Style)")%>
Controller Code -
ViewData["PropertyStyles"] = new SelectList(_typeRepository.GetPropertyStyles(), "TypeId", "TypeDescription", t);
www.almny.com said
can i get the source code for how to bind dropdownlist from mvc
http:// said
I have tried everything to get my Html.dropdownlist to work, but it's just not working.
Controller code:
Function Create() As ActionResult
Dim allCats = chchtvdc.GetCategories
ViewData("CategoryID") = New SelectList(allCats, "CategoryID", "CategoryName")
Dim allDifficulties = chchtvdc.GetDifficulties
ViewData("Difficulty") = New SelectList(allDifficulties, "DifficultyID", "DifficultyLevel")
Return View()
End Function
HTML:
<p>
<label for="DifficultyID">Difficulty:</label>
<% =Html.DropDownList("DifficultyID")%>
<%= Html.ValidationMessage("DifficultyID", "*") %>
</p>
<p>
<label for="CategoryID">Category:</label>
<%=Html.DropDownList("CategoryID")%>
<%= Html.ValidationMessage("CategoryID", "*") %>
</p>
I get the error:
There is no ViewData item with the key 'DifficultyID' of type 'IEnumerable<SelectListItem>'.
Any help will be appreciated.
http:// said
This also works but the main reason of dropdownlist not showing the selected value is that the page is beingposted back whenever a button is clicked and thus the page_load event handler is called which in turn resets the selected value property , so to rectify just check in the page_load handler that wthr it is being posted back or being loaded for the first time , by inserting if page.ispostback = false.
HeartattacK said
Shailja, this is about MVC, not webforms.
www.almny.com said
thanks for your reply
Deepak said
I am using 'SelectList' within in dropdown as below by sepcifying
1. Country object collection 2.valuefield 3.textfield 4.selectedValue (country object) which are exposed as properties in my View Model Object.Controller is filling up this properties after post back happens.But last value - 'selectedValue' is not working as expected.Controller is setting previosuly selected country to this property after post back but it is not binding to dropdown control after postabck.As result always first item of drop down is being selected by default.So why attribute 'selectedValue' not working ? Any idea/solution ?
<%= Html.DropDownList("Countries", new SelectList (Model.Countries,"Id","Name",Model.SelectedCountry))%>