BootStrap Metronic development framework-based experience summary [3] use of Select2 plug-in the drop-down list, metronicselect2
In the previous article, based on the BootStrap Metronic Development Framework experience summary [2] use of list paging processing and the JSTree plug-in, this article introduces the paging processing of data, uses the Bootstrap Paginator plug-in, and also on the tree list, using the JSTree plug-in, this article continues to introduce the control Select2 commonly used in editing pages. This control can enrich the traditional Select drop-down list controls and provide more functions and better user experience.
1. Introduction to the Select2 Control
This plug-in is a Select-based extension that provides richer features and user experience. Its github official website address is: release.
In the entire framework, we use a lot of Select2 controls to process content display, including the single-choice drop-down list (including cascading selection box), the check drop-down list, tree drop-down list, and other methods, the interface effect is as follows.
1) edit the cascading Interface Effects of provinces, cities, and administrative regions on the pageSelect a province. The city under the corresponding province is loaded. Select a city. The Administrative Region under the city is loaded to implement a multi-level association drop-down list.
2) multiple options drop-down list on the editing page
However, when we select the content, the system automatically displays the list of unselected data, which is very intuitive and friendly, as shown below.
3) tree list drop-down list
Sometimes, some of our data may be hierarchical, such as the organization or upper-layer list.
2. Code Analysis of Select2 controls
1) Basic interface code and operations
Use the select2 control. Generally, you can set it on the conventional select control (set its class to select2 ).
<Div class = "col-md-6"> <div class = "form-group"> <label class = "control-label col-md-4"> importance level </label> <div class =" col-md-8 "> <select id =" Importance "name =" Importance "class =" form-control select2 "placeholder =" important level... "> </select> </div> <div class =" col-md-6 "> <div class =" form-group "> <label class = "control-label col-md-4"> degree of Recognition </label> <div class = "col-md-8"> <select id = "Recognition" name = "Recognition" class = "form-control select2 "placeholder =" degree of recognition... "> </select> </div>
If it is a fixed list, you can set its Option content, as shown below.
<Div class = "col-md-6"> <div class = "form-group"> <label class = "control-label col-md-4"> smoke </label> <div class = "col-md-8 "> <select id =" Smoking "name =" Smoking "type =" text "class =" form-control select2 "placeholder =" Smoking... "> <option> smoking </option> <option> no smoking </option> </select> </div>
The simple select2 control initialization code is as follows.
$(document).ready(function() { $(".js-example-basic-single").select2();});
Generally, if multiple projects are allowed to be checked, set multiple = "multiple", as shown in the following code.
<select id="ResponseDemand" name="ResponseDemand" multiple="multiple" class="form-control select2"></select>
2) asynchronous data binding
Generally, the data of our select control is dynamically loaded from the database. Therefore, we can obtain and bind the data through Ajax.
Based on the consideration of code reusability, we compile a common JS function to reduce the code for binding operations and improve code reusability.
// Bind the dictionary content to the specified Select control function BindSelect (ctrlName, url) {var control = $ ('#' + ctrlName); // set the processing control of Select2. select2 ({allowClear: true, formatResult: formatResult, formatSelection: formatSelection, escapeMarkup: function (m) {return m ;}}); // bind Ajax content $. 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, the Select2 control is initialized and the corresponding dictionary value or other data is dynamically bound. You can use the following initialization code. BindDictItem directly binds the dictionary content, while BindSelect retrieves and binds data based on the URL, and $ ("# Province "). on ("change", function (e) {}); such function processing is to handle the linkage operation of the selected content changes.
// Initialize the dictionary information (drop-down list) function InitDictItem () {// for some assignments, see BindDictItem ("Area", "market partition"); BindDictItem ("Industry ", "Customer industry"); BindDictItem ("Grade", "customer level"); BindDictItem ("CustomerType", "customer type"); BindDictItem ("Source ", "Customer source"); BindDictItem ("CreditStatus", "credit grade"); BindDictItem ("Stage", "customer Stage"); BindDictItem ("Status ", "Customer status"); BindDictItem ("Importance", "important level"); // BindSelect ("Province", "/Provi Nce/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 );});}
Among them, the data returned by the MVC controller is a list of JSON data returned to the front-end page. 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 is bound to the Select2 control, the attributes of the JSON object are used.
// Bind Ajax content $. 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 controller implementation code is as follows:
/// <Summary> /// obtain the corresponding dictionary data based on the dictionary type, convenient UI control binding /// </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) tree list binding
For the attribute list, such as the affiliated company, department, and institution, its binding operation is 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 );});
Only the data they return is used as the display content with indentation.
[{"Text": "aiqidi group", "Value": "1" },{ "Text": "Guangzhou Branch", "Value": "3 "}, {"Text": "Shanghai Branch", "Value": "4" },{ "Text": "Beijing Branch", "Value": "5"}]
Or as follows:
[{"Text": "Guangzhou Branch", "Value": "3" },{ "Text": "General Manager", "Value": "6 "}, {"Text": "Finance Department", "Value": "7" },{ "Text": "Engineering Department", "Value": "8 "}, {"Text": "product R & D department", "Value": "9" },{ "Text": "Development Group", "Value": "14 "}, {"Text": "Development Group 2", "Value": "15" },{ "Text": "Test Group", "Value": "16 "}, {"Text": "Marketing Department", "Value": "10" },{ "Text": "Marketing Department", "Value": "23 "}, {"Text": "Market Department 2", "Value": "24" },{ "Text": "General Department", "Value": "11 "}, {"Text": "Production Department", "Value": "12" },{ "Text": "Human Resources Department", "Value": "13"}]
In summary, we can see that their Text content is increased by spaces based on hierarchies, so as to display hierarchies.
However, from the perspective of the interface effect, this kind of processing is indeed not in EasyUI, and the display of the drop-down list tree looks good. You may be able to use a better Bootstrap plug-in to display the tree content.
4) Assignment processing of the select2 Control
The methods described above describe the initialization and binding of the select2 control. If the interface is initialized and the value of the editing interface is bound, a value must be assigned to the control, show the project to be displayed.
The method for 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 you need to clear multiple controls, you can use the set for processing.
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 so that it displays the project of the corresponding value, so the operation is similar to the above.
$("#CustomerType").select2("val", info.CustomerType); $("#Grade").select2("val", info.Grade); $("#CreditStatus").select2("val", info.CreditStatus); $("#Importance").select2("val", info.Importance); $("#IsPublic").select2("val", info.IsPublic);
If cascade display is required, you can add an onchange function. The following cascade code assignment process is as follows.
$ ("# Province "). select2 ("val", info. province ). trigger ('change'); // linkage $ ("# City "). select2 ("val", info. city ). trigger ('change'); // linkage $ ("# 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, we will provide two holistic Interface Effects for your reference.
The above is a summary of the development framework experience based on BootStrap Metronic. [3] The Select2 plug-in the drop-down list is provided. I hope it will help you, if you want more information, please stay tuned to the help House website!