mvc dropdown list not retaining selected value

I am binding an MVC dropodown and filtering a list from the selected value of dropdown.

However the selected value is not being retained on postback.

I have an index view and the controller initially loads a full list.   I then have an index "post" method
that takes the selected ID from dropdown to filter the list.

The dropdown list is wrapped inside a form post tag like this

 <% using (Html.BeginForm("Index", "customers", FormMethod.Post, null))

Is this the correct approach?   I am sure it is something to do with postback
ToString1Asked:
Who is Participating?
 
khan_webguruCommented:
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"])%>

Open in new window


In my controller, I was setting the ViewData like this:

 
this.ViewData["categories"] = new SelectList(db.CategorySet.ToList(), "CategoryId", "Title", img.CategoryReference.EntityKey);

Open in new window


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

Open in new window


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.

Regards,

Asif Ahmed Khan
0
 
khan_webguruCommented:
Or you can look into this

http://www.isolutionteam.co.uk/asp-net-mvc-dropdown-selected-value/

Thats all from my side thanks
0
 
ToString1Author Commented:
OK thanks I will have a look.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.