mike_pl mike_pl - 1 month ago 5
ASP.NET (C#) Question

ASP.NET dropdown list options depends on chosen option in other dropdown list

I have simple ViewModel that I passed to view in my application, it has two SelectLists with several options like, e.g:

public class MyViewModel {

public SelectList Names { get; set;} // e.g options - N1,N2,N3

public SelectList Years { get; set;} // e.g options - Y1,Y2,Y3


}


There are several options defined for each of those SelecLists. In my view I have two DropDownListFor in which user can easily choose option - it's independent.

But what I want to do is that, when user choose in 1st dropdownlist option N1, then in second dropdown list will be available only options Y2,Y3. When user choose N2, in second one will appear only N3 etc.

Something with jQuery maybe? How to get information which option is currently chosen in particular dropdown list? With JavaScript?

Answer

Yes it ist possibile with javascript.

First you need to get the selected option from the dropdownlist by using javascript or Jquery for example like this:

yourSelect.options[ yourSelect.selectedIndex ].value

then you have to set an disabled attribute with either javascript or jquery.

The answer in this post here might be helpful.

Furthermore look at this example

If you want them to be completely deleted then you wolud need to take them out by deleteing the node using JQuery for example.

Comments