The second selected drop-down list item does not change in ASP.NET MVC

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?

+4
source share
1 answer

The reason for this does not work the way you expect, because when the DropDownList helper tries to display the select element, it first looks for the placed values ​​that match the name , which in this case are TwoID and use that value instead of the value in the model. Same thing with TextBox. If you use this helper and in the action of the POST controller you change the value of the model, it will still show the old value. This is how helpers work. They are associated with POSTED values.

Two workarounds are possible:

  • Use javascript to synchronize both dropdown menus:

     @onchange = "document.getElementById('TwoID').value = this.value; this.form.submit();" 

    By the way, this needs to be done in an unobtrusive way in a separate javascript file:

     $(function() { $('#OneID').change(function() { $('#TwoID').val($(this).val()); this.form.submit(); }); }); 
  • Write your own helper or create one manually (less recommended)

+1
source

Source: https://habr.com/ru/post/1300538/


All Articles