I am a little confused by the behavior of ASP.NET MVC without changing the value of the dropdown after POST. Can someone explain how to do this.
First of all, I have a model that looks like this:
public class Test { public int OneID { get; set; } public IEnumerable<SelectListItem> OneList { get { yield return new SelectListItem { Text = "Red", Value = "0" }; yield return new SelectListItem { Text = "Green", Value = "1" }; yield return new SelectListItem { Text = "Blue", Value = "2" }; } } public int TwoID { get; set; } public IEnumerable<SelectListItem> TwoList { get { yield return new SelectListItem { Text = "Ruby", Value = "0" }; yield return new SelectListItem { Text = "Gem", Value = "1" }; yield return new SelectListItem { Text = "Bronze", Value = "2" }; } } }
The view has this piece of code in the body content:
<% using (Html.BeginForm("Index", "Home", FormMethod.Post)) { %> <table> <tr> <td> <% =Html.DropDownList("OneID", Model.OneList, new { @onchange = "this.form.submit();" })%> </td> <td> <% =Html.DropDownList("TwoID", Model.TwoList)%> </td> </tr> </table> <% } %>
And the GET and POST actions are as follows:
public ActionResult Index() { Test test = new Test(); test.OneID = 0; test.TwoID = 0; return View(test); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(Test test) { test.TwoID = test.OneID; return View(test); }
What I'm trying to achieve is to change the selected item in the second drop-down list so that it matches the first drop-down list every time the first drop-down list changes. Therefore, I get the selected value from the first drop-down list and assign it to the identifier used for the second drop-down list, and then return the same model. The first snapshot is correctly set in the view, but not the second.
Ideas?
source share