Having a bit of an issue with a HtmlDropDownList in ASP.NET MVC when using a SelectList.
My issue is this, I have a database with records in for video clips, each record has a property called Type which is either Embedded 开发者_开发知识库or Youtube.
I then display these as editable records in a partial view. This works fine, upon initial page load all of the dropdown lists display the correct values for each record.
When I submit a change to a record by editing it and clicking Save on that row, it submits an AJAX form (using Ajax.BeginForm) which updates the entire panel with the entire partial view again - this should then reflect the changes as it re-grabs everything from the database.
However, when the page reloads/is updated, all of the dropdowns revert to the first item in the list as the default selected value... I can verify in the database that the values are still as they should be (i.e. they dont all change to the first value), and I can also confirm via breakpoints that before the view displays, all the values are coming through correctly.
Can anyone shed any light on this?
I am displaying the dropdown list like this:
<%=Html.DropDownList("Type", "Embedded,Youtube".ToSelectList(item.Type), new { style = "width: 100px;"})%>
The "ToSelectList" is just an extension method to create a select list from a comma seperated string, and the parameter is the value to be used as the selected value.
-
SOLUTION
The issue was, I was using "Type" as the name of the DropDownList so all of the dropdown lists had the same ID field, which meant they all took the same value. Instead, I changed them to "{item.ID}.Type" and then in my Controller I simply specified the Prefix for my UpdateModel statement as "{id}.".
var prefix = id.HasValue ? id.Value + "." : "";
UpdateModel(item, prefix, null, new[] { "Featured", "X-Requested-With" });
In the controller action that is serving this page you need to assign a value of Type
by reading it from the database:
ViewData["Type"] = ...
And because now I feel dirty for even mentioning ViewData
, the correct way of course would be to use view models and strongly typed helpers:
<%= Html.DropDownList(x => x.Type, Model.Types, new { style = "width: 100px;" }) %>
and then inside your controller action simply assign a value of the Type
property in your controller action to the correct value.
SOLUTION
The issue was, I was using "Type" as the name of the DropDownList so all of the dropdown lists had the same ID field, which meant they all took the same value. Instead, I changed them to "{item.ID}.Type" and then in my Controller I simply specified the Prefix for my UpdateModel statement as "{id}.".
var prefix = id.HasValue ? id.Value + "." : "";
UpdateModel(item, prefix, null, new[] { "Featured", "X-Requested-With" });
精彩评论