MVC5 in the background to provide JSON, the foreground processing JSON, binding to the DropDownList example:
Front:
We previously defined two controls on the front end:
<Divclass= "Row"> <Divclass= "Col-md-1">Countries</Div> <Divclass= "Col-md-11">@Html. dropdownlistfor (model = model. Director.hometownid, MvcEntitiyFrameWork.ViewModels.HometownViewModel.GetHometownSelectList (), Htmlattributes: New {@class = "Form-control", @style = "width:120px;"}) </Div> </Div> <Divclass= "Row"style= "margin-bottom:2px"> <Divclass= "Col-md-1">Director</Div> <Divclass= "Col-md-11">@Html. dropdownlistfor (model = model. Directorid, MvcEntitiyFrameWork.ViewModels.DirectorViewModel.GetDirectorSelectList ( Model.Director.HometownID.ToString ()), htmlattributes:new {@class = "Form-control", @style = "width:120px;"}) @Html. validationmessagefor (model = model. Directorid, "", new {@class = "Text-danger"})</Div> </Div>
We then execute the following code in the script:
In particular, we do not seem to specify the ID of the control in the code above, but the ID of the control will be visible to the page after it is run, so I can get the ID from the running interface.
<script type= "Text/javascript" > $("#Director_HometownID"). Change (function() {Getdirector ($ ( This). Val ()); } ); functiongetdirector (message) {varoption ={URL:'/movies/getdirectorlist ', type:' Get ', Chche:false, DataType:' JSON ', data: {_htid:message},//Sending server DataSuccessfunction(data) {//Success Events$ ("#DirectorID"). empty (); $.each (data,function(I, Item) {$ ("<option></option>"). Val (Data[i]. Value). Text (Data[i]. Text). AppendTo ($ ("#DirectorID")); }); }, Error:function(XMLHttpRequest, Textstatus, Errorthrown) {//Send failed Eventalert (textstatus); } }; //for asynchronous transfers$.ajax (option); } </script>
Our backstage, controller is defined as follows, return ActionResult
PublicActionResult Getdirectorlist (string_htid) { Try { //method One Ok//var selectlist = db. Directors.where (A = a.hometownid.tostring () = = _htid). Select (a = new SelectListItem//{ //Text = A.directorname,//Value = a.directorid.tostring ()//}); //return Json (SelectList, jsonrequestbehavior.allowget); //method Two also OKlist<director> list = db. Database.sqlquery<director> ("Select Directorid,directorname,hometownid from directors where hometownid= '"+ _htid +"'"). ToList (); SelectList pList=NewSelectList (list,"Directorid","Directorname"); returnJson (pList, jsonrequestbehavior.allowget); } Catch(Exception ex) {return NULL; } }
The front end can get the return value, bind the Dropdownlistbox data (here is the application of Dropdownlistbox Cascade filter data)
MVC5 in the background json, the foreground processing JSON, binding to the DropDownList example