@Html.DropDo...">

Removing an item from the dropdownlist helper list

I have a view containing two @Html.DropDownListFor :

  <div class="editor-field"> @Html.DropDownListFor(model => model.Employee, (IEnumerable<SelectListItem>)ViewBag.emps, "--Select--", new { style = "width:150px", id = "ddl1"}) @Html.ValidationMessageFor(model => model.Employee) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.Employee2, (IEnumerable<SelectListItem>)ViewBag.emps, "--Select--", new { style = "width:150px", id = "ddl2"}) @Html.ValidationMessageFor(model => model.Employee2) </div> 

They are filled as follows:

 public ActionResult Create() { List<Employees> emps = new List<Employees>(); emps.Add(new Employees { Id = 0, Name = "Michael Jordan" }); emps.Add(new Employees { Id = 1, Name = "Magic Johnson" }); emps.Add(new Employees { Id = 2, Name = "Larry Bird" }); var items = emps.Select(i => new SelectListItem { Value= i.Id.ToString(), Text =i.Name }); ViewBag.emps = items; return View(); } 

How to remove selected item from first DDL from second DDL? I managed to get the selected item using jQuery as follows:

 <script type="text/javascript"> $(function () { $("#ddl1").change(function () { alert($("#ddl1").val()); }); }); </script> 

However, I could not find a way to use it for my purpose.

+4
source share
2 answers

Something like this should work for you:

 $(function(){ var lists = $('#ddl1, #ddl2'); lists.change(function(){ var elm = $(this); lists.find('option').show(); var option = lists.not('#' + this.id) .find('option[value="' + elm.val() +'"]').hide(); if(option.is(':selected')) { var select = option.closest('select'); select.val(select.find('option:visible:first').val()); } }); }); 

Demo Link: jsfiddle.net

Added: The proposed solution has problems with IE, an alternative way is to disable the attribute: jsfiddle.net/cxZ2H/1/

+3
source

This is definitely a client side scripting issue, not a server side ASP.NET MVC issue.

Here is my tip:

  • Create a list of your products on the server side.
  • But when you bring it to the customer, keep an immutable master copy. Use it to populate your first select .
  • When the user selects an item from the first list, create a clone of the first list, minus the selected item.

Here's JSFiddle: http://jsfiddle.net/Fsf7g/1/

+2
source

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


All Articles