Asp.net MVC, Html.DropDownList and Selected Value

by ashic 26. March 2009 23:53

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.

Share or Bookmark this post…
  • DotNetKicks
  • LinkedIn
  • Technorati
  • msdn Social
  • del.icio.us
  • Digg
  • Reddit
  • StumbleUpon
  • Slashdot
  • Live
  • Google
  • Facebook
Categories: ASP.NET | ASP.NET MVC

Comments

3/9/2009 12:14:59 AM #

Thanks very much. This seems to be the only example any where on the internet where the viewdata is cast to IEnumerable in the markup!

Martin Evans

3/11/2009 8:28:05 AM #

http://

Can you show the related code? i.e., CategorySet, CategoryReference, the controller method code?

http://

4/5/2009 4:03:57 PM #

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();

HeartattacK

4/7/2009 2:43:13 AM #

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);

Matt

4/15/2009 1:57:51 AM #

can i get the source code for how to bind dropdownlist from mvc

www.almny.com

4/22/2009 1:45:42 PM #

http://

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:


                
                <% =Html.DropDownList("DifficultyID")%>
                <%= Html.ValidationMessage("DifficultyID", "*") %>


            


                
                <%=Html.DropDownList("CategoryID")%>
                <%= Html.ValidationMessage("CategoryID", "*") %>
            




I get the error:

There is no ViewData item with the key 'DifficultyID' of type 'IEnumerable'.

Any help will be appreciated.

http://

4/23/2009 8:34:46 AM #

http://

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.

http://

4/23/2009 8:59:37 PM #

Shailja, this is about MVC, not webforms.

HeartattacK

5/10/2009 4:13:16 AM #

thanks for your reply

www.almny.com

9/9/2009 1:07:11 AM #

Deepak

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))%>

Deepak India

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading




Powered by BlogEngine.NET 1.5.1.29
Theme by Ashic Mahtab

Stats