I am using ASP.Net MVC 2 and am having difficulty binding DropDownList.
I am using a strongly typed ViewModel and an HTML.DropDownListFor statement to create a drop-down list in my view. The application works fine in a “normal” scenario, when I just bind DropDown to a simple field in my ViewModel. I had a problem using this script when my ViewModel contains a list (array) of several objects in which I want the field of each of these objects to be associated with a (separate) DropDown. In this case, DropDown does not receive the correct initial value.
For example, the case when we have a person who can have several addresses. Each address consists of a street, city, and state. I want the state to display as DropDown. My model:
public class PersonModel : CommonViewModel
{
public IList<SelectListItem> AvailableStates { get; set; }
public string Name { get; set; }
public IList<AddressModel> Addresses { get; set; }
public PersonModel()
{
AvailableStates = GenerateStates();
}
private IList<SelectListItem> GenerateStates()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = "WA", Value = "WA" });
items.Add(new SelectListItem() { Text = "NY", Value = "NY" });
items.Add(new SelectListItem() { Text = "IH", Value = "IH" });
items.Add(new SelectListItem() { Text = "FL", Value = "FL" });
items.Add(new SelectListItem() { Text = "CA", Value = "CA" });
return items;
}
}
public class AddressModel
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
Now in my view I want to use something like:
<% using (Html.BeginForm("SubmitPersonDetails", "Home", new { actionMode = "Person"}, FormMethod.Post, new { id = "SubmitPersonForm" }))
{%>
<div class="formrow longinput">
<%= Html.LabelFor(person => person.Name)%>
<%= Html.TextBoxFor(person => person.Name)%>
</div>
<h4>Addresses</h4>
<% for (int i = 0; i < Model.Addresses.Count; i++) { %>
<div class="formrow">
<%= Html.TextBoxFor(person => person.Addresses[i].Street)%>
<%= Html.TextBoxFor(person => person.Addresses[i].City)%>
<%--<%= Html.TextBoxFor(person => person.Addresses[i].State)%>--%>
<%= Html.DropDownListFor(person => person.Addresses[i].State, Model.AvailableStates) %>
</div>
<% } %>
<input class="button primary" type="submit" value="Submit" name="Submit" />
<% } %>
For text fields, this works fine (also, if I just use a text field for state, see the comment). DropDown generated correctly, but not set to the correct value. If I select a value in DropDowns and submit the form, the correct values will return to my model.
UserControl, . UserControl Html.RenderPartial, DropDOwn, Postback . UserControl, EditorFor, , : DropDown , Postback , .
, , - , (: Address1, Address2, Address3), : <% = Html.DropDownListFor(person = > person.Address1.State, Model.AvailableStates)% > DropDown . , - .
? MVC, , , ?