This article has documented a small example of using Partialview in MVC4 to achieve cascading effects.
preparatory work
First, prepare the data to cascade, create a new two classes: Province and City
Public classProvince { Public stringId {Get;Set; } Public stringName {Get;Set; } } Public classCity { Public stringId {Get;Set; } Public stringName {Get;Set; } Public stringProvince {Get;Set; } }
and prepare the data in the controller,
List<province> provincelist =NewList<province>(); List<City> citylist =NewList<city>(); Private voidInitData () {Provincelist.add (NewProvince {Id ="1", Name ="Hebei province" }); Provincelist.add (NewProvince {Id ="2", Name ="Henan Province" }); Provincelist.add (NewProvince {Id ="3", Name ="Guangdong province" }); Citylist.add (NewCity {Id =" One", Name ="Shijiazhuang", province ="1" }); Citylist.add (NewCity {Id =" A", Name ="Xingtai", province ="1" }); Citylist.add (NewCity {Id =" -", Name ="Baoding", province ="1" }); Citylist.add (NewCity {Id =" +", Name ="Zhengzhou", province ="2" }); Citylist.add (NewCity {Id =" A", Name ="Anyang", province ="2" }); Citylist.add (NewCity {Id =" at", Name ="Luoyang", province ="2" }); Citylist.add (NewCity {Id =" to", Name ="Guangzhou", province ="3" }); Citylist.add (NewCity {Id =" +", Name ="Zhongshan", province ="3" }); Citylist.add (NewCity {Id =" -", Name ="Foshan", province ="3" }); }
Controller
Create an action in the controller that returns the step-by view, which triggers the action at the first level of the foreground and returns the data required by the second level.
Public ActionResult showcity (string Provinceid) { initdata (); var result = Citylist.where (city = city. Province = = Provinceid) ; = result; return Partialview ("partialcity"); }
View
First create a PartialView:PartialCity.cshtml, as follows:
@{ "partialcity";} City: @Html. DropDownList ("city_dropdownlist"new"Id " " Name "))
Using this partialview in the main view,
<div id="Province">province: @Html. DropDownList ("province_dropdownlist",NewSelectList (Viewbag.province,"Id","Name")) </div> <div id=" City">@Html. Partial ("partialcity") </div>
Finally, you need to write a few lines of JS code on the main view page, register a Change event for the first level DropDownList, and invoke the Showcity method you just created when the event is triggered.
@Scripts. Render ("~/scripts/jquery-1.7.1.min.js");<script type="Text/javascript">$ (document). Ready (init); function init () {$ ("select[name= ' province_dropdownlist ']"). Change (function () {varSelectedprovince = $ ( This). Val (); Showcitywithselectedprovince (selectedprovince); }); } function showcitywithselectedprovince (province) {$.ajax ({URL:"@Url. Action ("Showcity", "Home")", data: {provinceid:province}, success:function (data) {$ ("#city"). HTML (data); } }); }
In this way, cascading effects are achieved.
Above
Cascading with Html.dropdownlist in MVC4