Select2使用方法汇总
引用:
<script src="~/Content/plugins/select2/select2.min.js"></script>
1.简单使用
$.getJSON("/Basic/GetWareList", {}, function(data) { $("#form_ware").select2({ data: data });
});
--根据value选中
$("#form_ware").val('20007').trigger("change");
--根据text选中
$("#form_ware option:contains('华南仓')").attr('selected', true).trigger("change");
--清空
$("#form_ware").empty();
--取值
$("#form_ware").select2('data')[0].id;
$("#form_ware").select2('data')[0].text;
$("#form_ware").select2('data')[0].obj; //获取附加值
2.级联使用
初始化信息
$("#form_province").select2({
data: [{ id: -1, text: "请选择" }]
});
省市县级联
//初始化地址信息 $("#dl_province").select2({ data: [{ id: -1, text: "请选择" }] }); $("#dl_city").select2({ data: [{ id: -1, text: "请选择" }] }); $("#dl_county").select2({ data: [{ id: -1, text: "请选择" }] }); //加载省 $.getJSON("/Basic/GetAddressList", { type: "2", parent_id: "1", default_text: "请选择" }, function (data) { $("#dl_province").select2({ data: data }); }); //加载市 $("#dl_province").change(function (e) { $("#dl_city").empty(); $("#dl_city").select2({ data: [{ id: -1, text: "请选择" }] }); $("#dl_county").empty(); $("#dl_county").select2({ data: [{ id: -1, text: "请选择" }] }); var dl_province = $("#dl_province option:selected").val(); if (dl_province != "-1") { $.getJSON("/Basic/GetAddressList", { type: "3", parent_id: dl_province, default_text: "请选择" }, function (data) { $("#dl_city").select2({ data: data }); }); } }); //加载县 $("#dl_city").change(function (e) { $("#dl_county").empty(); $("#dl_county").select2({ data: [{ id: -1, text: "请选择" }] }); var dl_city = $("#dl_city option:selected").val(); if (dl_city != "-1") { $.getJSON("/Basic/GetAddressList", { type: "4", parent_id: dl_city, default_text: "请选择" }, function (data) { $("#dl_county").select2({ data: data }); }); } });
3.后端帮助方法
public class ToSelect2Data<T> where T : class { public static List<Select2DataModel<T>> ToSelectData(List<T> model, string IdKey, string TextKey) { List<Select2DataModel<T>> m = new List<Select2DataModel<T>>(); foreach (var item in model) { Type t = item.GetType(); Select2DataModel<T> s = new Select2DataModel<T>(); PropertyInfo idInfo = t.GetProperty(IdKey); s.id = idInfo.GetValue(item, null).ToString(); PropertyInfo textInfo = t.GetProperty(TextKey); s.text = textInfo.GetValue(item, null).ToString(); s.obj = item; m.Add(s); } return m; } } public class Select2DataModel<T> where T : class { public string id { get; set; } public string text { get; set; } public T obj { get; set; } }
使用方法(id,name 是list集合的字段名)
return Json(ToSelect2Data<bs_addr>.ToSelectData(addressList, "id", "name"), true);