In the previous article, the experience summary of the development framework based on BootStrap Metronic [II] list pagination processing and the use of plug-in JSTree, the data pagination processing was introduced, the Bootstrap Paginator plug-in was used, and the tree list was used, the JSTree plug-in was used. This article continues to introduce the commonly used control Select2 in the edit page. This control can enrich the traditional Select drop-down list control, providing more functions and a better user experience.
1. Introduction to Select2 control
This plug-in is an extension plug-in based on Select, which can provide richer functions and user experience. Its official github website address is: https://select2.github.io/. For specific use cases, please refer to the address: https://select2.github.io/examples.html.
In the entire framework, we have used many Select2 controls to handle the display of content, including a single-select drop-down list (including a cascading selection box), a selected drop-down list, a tree drop-down list, etc. The interface effect is as follows.
1) The cascading interface effect of provinces, cities, and administrative regions under the editing interface . If you select a province, the city under the corresponding province will be loaded. If you select a city, the administrative regions under the city will continue to load, thereby achieving the drop-down list effect of multi-level correlation.
2) Multiple selection drop-down list under the editing interface
But when we select the content, the system will automatically display the list data without selection, which is very intuitive and friendly, as shown below.
3) Drop-down list of tree list
Sometimes, some of our data may have hierarchical relationships, such as the organization, the upper-level list, etc.
2. Analysis of the actual usage code of Select2 control
1) Basic interface code and operation
Use the select2 control, usually on the regular select control, just set it (set its class to select2).
<div> <div> <label>Important Level</label> <div> <select id="Importance" name="Importance" placeholder="Importance..."></select> </div> </div></div> <div> <div> <label>Recognition</label> <div> <select id="Recognition" name="Recognition" placeholder="Recognition..."></select> </div> </div></div>
If it is a fixed list, then it is just set its Option content, as shown below.
<div> <div> <label>Smoking</label> <div> <select id="Smoking" name="Smoking" type="text" placeholder="Smoking..."> <option>Smoking</option> <option>Don't smoke</option> </select> </div> </div></div>
The simple select2 control initialization code is as follows.
$(document).ready(function() { $(".js-example-basic-single").select2();});Generally speaking, if multiple items are allowed to be selected, then set multiple="multiple" as shown in the following code.
<select id="ResponseDemand" name="ResponseDemand" multiple="multiple"></select>
2) Asynchronous data binding operation
Generally speaking, the data of our select control is loaded dynamically from the database, so the data is usually obtained and bound through Ajax.
Based on the consideration of code reusability, we write a common JS function to reduce the code of binding operations and improve code reusability.
//Bind dictionary content to the specified Select control function BindSelect(ctrlName, url) { var control = $('#' + ctrlName); //Set Select2's processing control.select2({ allowClear: true, formatResult: formatResult, formatSelection: formatSelection, escapeMarkup: function (m) { return m; } }); //Bind the content of Ajax $.getJSON(url, function (data) { control.empty();//Clear the drop-down box $.each(data, function (i, item) { control.append("<option value='" + item.Value + "'>" + item.Text + "</option>"); }); }); });In this way, the data bound to the public dictionary module can be further encapsulated and processed as follows.
//Bind the dictionary content to the specified control function BindDictItem(ctrlName, dictTypeName) { var url = '/DictData/GetDictJson?dictTypeName=' + encodeURI(dictTypeName); BindSelect(ctrlName, url);}In this way, we initialize the Select2 control and dynamically bind the corresponding dictionary value or other data. This can be achieved through the following initialization code. Among them, BindDictItem is the operation that directly binds the dictionary content, BindSelect is the operation that obtains and binds data based on the URL, and $("#Province").on("change", function (e) {}); is the operation of function processing such as $("#Province").on("change", function (e) {}); handles the linkage operation that handles the changes in the selected content.
//Initialize dictionary information (drop-down list) function InitDictItem() { //Second assignment reference BindDictItem("Area","Market partition"); BindDictItem("Industry", "Customer industry"); BindDictItem("Grade","Customer level"); BindDictItem("CustomerType", "Customer type"); BindDictItem("Source", "Customer source"); BindDictItem("CreditStatus", "Credit rating"); BindDictItem("Stage", "Customer stage"); BindDictItem("Status", "Customer status"); BindDictItem("Importance", "Importance Level"); // Bind province, city, and administrative region (linkage processing) BindSelect("Province", "/Province/GetAllProvinceNameDictJson"); $("#Province").on("change", function (e) { var provinceName = $("#Province").val(); BindSelect("City", "/City/GetCitysByProvinceNameDictJson?provinceName="+ provinceName); }); $("#City").on("change", function (e) { var cityName = $("#City").val(); BindSelect("District", "/District/GetDistrictByCityNameDictJson?cityName="+ cityName); }); }As for the data returned by the MVC controller, we return a JSON data list to the front-end page, and their data format is as follows.
[ { "Text": "", "Value": "" }, { "Text": "Academic Conference", "Value": "Academic Conference" }, { "Text": "Friend Introduction", "Value": "Friend Introduction" }, { "Text": "Advertising Media", "Value": "Advertising Media" } ]In this way, when the front-end page binds the Select2 control, the properties of the JSON object are used.
//Bind the content of Ajax $.getJSON(url, function (data) { control.empty();//Clear the drop-down box $.each(data, function (i, item) { control.append("<option value='" + item.Value + "'>" + item.Text + "</option>"); }); });The implementation code of the controller is as follows:
/// <summary> /// Get the corresponding dictionary data according to the dictionary type to facilitate binding of UI controls /// </summary> /// <param name="dictTypeName">Dictionary type name</param> /// <returns></returns> public ActionResult GetDictJson(string dictTypeName) { List<CListItem> treeList = new List<CListItem>(); CListItem pNode = new CListItem("", ""); treeList.Insert(0, pNode); Dictionary<string, string> dict = BLLFactory<DictData>.Instance.GetDictByDictType(dictTypeName); foreach (string key in dict.Keys) { treeList.Add(new CListItem(key, dict[key])); } return ToJsonContent(treeList); }3) Binding operation of tree list
For attribute lists, such as hierarchical data of their affiliated companies, departments and institutions, their binding operations are also similar, as shown in the following code.
//BindSelect("Company_ID", "/User/GetMyCompanyDictJson?userId="+@Session["UserId"]); $("#Company_ID").on("change", function (e) { var companyid = $("#Company_ID").val(); BindSelect("Dept_ID", "/User/GetDeptDictJson?parentId="+ companyid); }); $("#Dept_ID").on("change", function (e) { var deptid = $("#Dept_ID").val(); BindSelect("PID", "/User/GetUserDictJson?deptId="+ deptid); });It's just the data they return, we just use it as indented display content.
[ { "Text": "iqidi Group", "Value": "1" }, { "Text": "Guangzhou Branch", "Value": "3" }, { "Text": "Shanghai Branch", "Value": "4" }, { "Text": "Beijing Branch", "Value": "5" } ]Or as shown below
[ { "Text": "Guangzhou Branch", "Value": "3" }, { "Text": "General Manager's Office", "Value": "6" }, { "Text": "Financial Department", "Value": "7" }, { "Text": "Engineering Department", "Value": "8" }, { "Text": "Product R&D Department", "Value": "9" }, { "Text": "Develop a Group", "Value": "14" }, { "Text": "Develop a Group 2", "Value": "15" }, { "Text": "Test Group 2", "Value": "15" }, { "Text": "Test Group 2", "Value": "16" }, { "Text": "Market Department", "Value": "10" }, { "Text": "Market Department 1", "Value": "23" }, { "Text": "Market Department 2", "Value": "24" }, { "Text": "Comprehensive Department", "Value": "11" }, { "Text": "Production Department", "Value": "12" }, { "Text": "Human Resources Department", "Value": "13" } ]To sum up the above two parts, we can see that the content of their Text is to increase spaces according to the hierarchical relationship, thereby realizing the display of the hierarchical relationship.
However, in terms of the interface effect, this processing is indeed not as good as the display of the drop-down list tree in EasyUI. Perhaps a better Bootstrap plug-in can be used to display this tree-shaped content.
4) Assignment processing of select2 control
The methods introduced above are all about initializing the select2 control and binding related data. So if we bind the value of the editing interface after initializing the interface, we need to assign the value to the control to let it display the items that really need to be displayed.
The method of clearing the control is as follows.
//Clear the value of the Select2 control $("#PID").select2("val", ""); $("#Company_ID").select2("val", ""); $("#Dept_ID").select2("val", "");If multiple controls need to be cleared, you can use the collection to process it
var select2Ctrl = ["Area","Industry","Grade","CustomerType","Source","CreditStatus","Stage","Status","Importance"]; $.each(select2Ctrl, function (i, item) { var ctrl = $("#" + item); ctrl.select2("val", ""); });Assign a value to the Select2 control to display the items with the corresponding value content, and the operation will be similar to the above.
$("#CustomerType").select2("val", info.CustomerType); $("#Grade").select2("val", info.Grade); $("#CreditStatus").select2("val", info.CreditStatus); $("#Importance").select2("val", info.IsPublic);If you need to display it in a cascading way, then add an onchange function processing, as follows the assignment processing of the following cascading code.
$("#Province").select2("val", info.Province).trigger('change');//Link $("#City").select2("val", info.City).trigger('change');//Link $("#District").select2("val", info.District); $("#Company_ID1").select2("val", info.Company_ID).trigger('change'); $("#Dept_ID1").select2("val", info.Dept_ID).trigger('change'); $("#PID1").select2("val", info.PID);Finally, there are two integrated interface effects for reference.
The above is the summary of the experience of the BootStrap Metronic development framework based on the [Three] drop-down list of the relevant content of the use of the Select2 plug-in. I hope it will be helpful to everyone. If you want to know more information, please pay attention to the Wulin.com website!