MVC Dropdown lists bound depending on the value of another dropdown list
I am trying to write an MVC webpage that has two drop down lists. The content of the s开发者_如何学编程econd list depends on what is selected in the first.
There does not seem to be a definitive way of doing this using built in MVC functions so I am going to have to roll my own. However I am not clear on the best way of getting all the functionality I require... which is "be the same as webforms" :)
I have created the dropdowns in a way similar to this
However I am not sure how to develop this so that if there is a 'selected' element in the first list when it is first bound this will flow through to automatically binding the second list on page load.
Edit: Just to be clear I have the ability to bind the filtered list to the second dropdown. However if my Model contains a selection for the first dropdown the selection is set correctly but the second dropdown list does not fill.
(do I have to state I am newish to MVC and Javascript is like some alien language to me?)
Edit2: I have thought about this a bit more. Clearly I am strongly influenced by my time developing webforms and I don't quite 'get' MVC yet. I think that really I have some things I should be catching in my model (ie if I already have the info to set the two dropdowns then I should in some way catch that in the controller and build the dropdowns pre set. Rather than trying to build an "ondatabound" type method and have the view call that (which was my initial intent)... Now I need to go and work out how to do that :)
This is one of the better implementations that I found. The question has also been discussed here.
You task contains 3 subtasks:
- You should ajax get list of items for second ddl on changing selection of first ddl by using selected value
- You should process action of getting list of items for 2-nd ddl by your Controller and return View with defined content of second ddl
- You should update content of second ddl by getting result of processed action
<script type="text/javascript">
$(function(){ $("form #ddl_1").change(function(){ $.get({ // get request url: "@Url.Action("MyController", "GetList"})" + "/" + $(this).val, success: function(data){ // updating $("form #ddl_2").html(data); } }) });
</script>
"GetList" action should take parameter "id" if you use default routes table (or you need to create special record at routes table with custom) and return partial view (without master page) with list of options for your ddl2, like this:
<option value="1">First</option>
<option selected value="2">Second</option>
<option value="3">Third</option>
See this blog post for creating cascading dropdown lists in asp.net mvc with downloadable source code.
精彩评论