Web開發框架使用Ajax實現dropdownlist聯動
阿新 • • 發佈:2018-12-28
Html下拉框主要體現在select標籤和option標籤,
Web開發平臺中我們使用mvc html擴充套件方法@Html.DropDownListFor()來 輕鬆繫結下拉列表屬性值,我們已一段程式碼說明給下拉列表來怎麼動態賦值。
說明
頁面程式碼
資料模型
Ajax聯動
後臺action
結語
頁面程式碼
資料模型
Ajax聯動
後臺action
結語
說明
我們通過Web開發框架兩個下拉列表賦值案例來說明,下拉框1值通過屬性值繫結AvailableCategories直接從後臺獲取,下拉框2值SensorList實現與下拉框1值變化而聯動。
頁面程式碼
<div class="form-group row"> <div class="col-md-2"> <label>下拉框1:</label> </div> <div class="col-md-2"> @Html.DropDownListFor(model => model.Cid, Model.AvailableCategories, new { @class = "form-control" }) </div> <div class="col-md-2"> <label>下拉框2:</label> </div> <div class="col-md-2"> @Html.DropDownListFor(model => model.Sensor, Model.SensorList, new { @class = "form-control" }) </div> </div>
資料模型
/// <summary> /// 下拉框1 /// </summary> public IList<SelectListItem> AvailableCategories { get; set; } /// <summary> /// 下拉框1值 /// </summary> [NopResourceDisplayName("Search.Category")] public int Cid { get; set; } /// <summary> /// 下拉框2 /// </summary> public List<SelectListItem> SensorList { get; set; } /// <summary> /// 下拉框2值 /// </summary> [AllowHtml] public string Sensor { get; set; } Ajax聯動 $(function () { $('#Cid').change(function () { var data = "cid=" + $(this).val(); var disoptioan = { url: "@Url.Action("GetCamaraSensors", "Catalog")", type: 'Get', dataType: 'json', data: data, context: this, success: function (result) { $("#Sensor").empty(); for (var i = 0; i < result.length; i++) { var text = result[i].Text; var value = result[i].Value; $("#Sensor").append(new Option(text, value)); } } }; $.ajax(disoptioan); }); });
後臺action
public ActionResult GetCamaraSensors(int cid) { IList<SelectListItem> sensorsList = new List<SelectListItem>(); sensorsList.Add(new SelectListItem { Text = _localizationService.GetResource("common.selected"), Value = "0" }); List<ProductCategory> productCategories = _categoryService.GetProductCategoriesByCategoryId(cid, 0, int.MaxValue).ToList(); productCategories.ForEach(p => { sensorsList.Add(new SelectListItem { Text = p.Product.Name, Value = p.ProductId.ToString() }); }); return Json(sensorsList, JsonRequestBehavior.AllowGet); }
結語
1、AvailableCategories中SelectListItem是一個有text和mvalue特性的類,web開發平臺中通過ViewModel繫結賦值給下拉框1。
2、SensorList中SelectListItem是一個有text和mvalue特性的類,通過Ajax非同步從後臺獲取列表值後動態繫結賦值給下拉框2。
3、Web開發框架Ajax程式碼說明:下拉框1值改變後觸發js change事件,通過ajax非同步提交查詢獲取查詢結果,success回撥函式中賦值給下拉框2。
4、執行結果: