This article introduces a cascade drop-down list using ASP. net mvc + Ajax, which can return user-selected data in real time. For more information, see.
Front-end template file, giving the first initial drop-down list initial value, the second does not have data, return json data binding through Ajax call background
The Code is as follows: |
Copy code |
@ Html. dropDownList ("CategroyID", (IEnumerable <SelectListItem>) ViewBag. categoryID, "select... ", new {id =" CategroyID ", onchange =" GetArticleClass (this )"}) <Select id = "ArticleClassID" name = "ArticleClassID"> <Option value = ""> Select... </option> </Select> <Script type = "text/javascript"> Function GetArticleClass (id ){ $ ("# ArticleClassID"). empty (); // clear the city SELECT Control $. Ajax ({ Url: '/home/GetArticleClass/' + $ ("# CategroyID"). val (), Type: "get ", Datatype: "json ", Success: function (data ){ If (data. length = 0 ){ $ ("<Option> </option> ") . Val ("0 ") . Text ("Select ...") . AppendTo ($ ("# ArticleClassID ")); } $. Each (data, function (I, item ){ $ ("<Option> </option> ") . Val (item ["ID"]) . Text (item ["Name"]) . AppendTo ($ ("# ArticleClassID ")); }); } }); } </Script> |
Background Method
The Code is as follows: |
Copy code |
Public ActionResult GetArticleClass (int id = 0) { List <ArticleClassModels> articleClass = db. ArticleClass. Where (a => a. CategoryID = id). ToList (); Return Json (articleClass, JsonRequestBehavior. AllowGet ); } |
Notes
The ArticleClassModels model includes attributes such as ID and Name.