ASP.NET下拉選單DropDownList套用jQuery複合選取時的經驗談(改採ListBox較適合)

 
Multiple Select is a jQuery plugin to select multiple elements with checkboxes



雖然DropDownList預設Render到HTML對應產生SELECT的HTML TAG
但是Code-Behind中要透過SelectedValue取得只能取得到第一個選到的唯一值

https://docs.microsoft.com/zh-tw/dotnet/api/system.web.ui.webcontrols.dropdownlist?view=netframework-4.8#properties




原因在於Multiple Select這項jQUery plugin背後實作只是將select 的 display設置為none
然後自行在render出來上下兩組div做特殊處裡


因此這裡必須捨棄掉dropdownlist的控件相關屬性、方法處理

首先
先有辦法監聽到每次check/unckeck項目的值


jQuery MultipleSelect code範本

See the Pen jQuery Multiple Select by Jacob (@dryjoker) on CodePen.


這裡要注意使用的MultipleSelect版本有差異!!!
像是這裡我用官網cdn使用
它裡面選中是定義成selected

而我這裡專案的定義則是 checked!!!!


建議都先console印出來裏面的屬性有哪些


.aspx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
$('#<%=ddl_multi.ClientID%>').multipleSelect({
    placeholder: "法人單位(可複選)",
    width: '99%',
    selectAll: false,
    multiple: true,
    multipleWidth: 150,
    onClick: function(v) { //Fires when a checkbox is checked or unchecked.
        //console.log("item checked");
        console.log(v);
        console.log(v.value);
        console.log(v.checked);
        console.log(v.checked === true);
        let opType = "";
        if (v.checked === true) {
            opType = "add";
        } else {
            opType = "remove";
        }

        console.log('{operateMode: "' + opType + '",val:"' + v.value + '" }');

        $.ajax({
            type: "POST",
            url: "/SubWin/MemberRegisterSub.aspx/SaveMultiSelectList",
            contentType: "application/json;charset=utf-8",
            data: '{operateMode: "' + opType + '",val:"' + v.value + '" }',
            dataType: "json",
            success: function(data) {
                if (data.d == "success") {
                    console.log("save check list successfully");
                } else {
                    //alert(data.d);
                    console.log("save check list not return success");
                    console.log(data.d);
                }
            },
            error: function(xhr, status, error) {
                //alert("API Error");
                console.log(xhr.responseText);
            }
        });

    }
});


.aspx.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[System.Web.Services.WebMethod(EnableSession = true)]
public static string SaveMultiSelectList(string operateMode, string val)
{
    string result = "success";
    if (operateMode.Equals("add"))
    {
        if (System.Web.HttpContext.Current.Session["multiSelectList"] == null)
        {
            List<string> lsMulTiSelect = new List<string>();
            lsMulTiSelect.Add(val);
            System.Web.HttpContext.Current.Session["multiSelectList"] = lsMulTiSelect;
        }
        else
        {
            List<string> lsMulTiSelect = (List<string>)System.Web.HttpContext.Current.Session["multiSelectList"];
            lsMulTiSelect.Add(val);
            System.Web.HttpContext.Current.Session["multiSelectList"] = lsMulTiSelect;
        }
    }
    else if (operateMode.Equals("remove"))
    {
        if (System.Web.HttpContext.Current.Session["multiSelectList"] == null)
        {
            result = "";
        }
        else
        {
            List<string> lsMulTiSelect = (List<string>)System.Web.HttpContext.Current.Session["multiSelectList"];
            lsMulTiSelect.Remove(val);
            System.Web.HttpContext.Current.Session["multiSelectList"] = lsMulTiSelect;
        }
    }
    else
    {
        result = "";
    }
    return result;
}


透過每次選完觸發ajax調用後台WebMethod 
利用session存選取值列表加以進行增減更新

這裡要注意在靜態的WebMethod中無法使用ViewState
以上

#2021/10/22更新
若要套用MultiSelecy的其實應該改用ListBox才比較適合在ServerSide做存取跟Data Bind
ListBox 有一個 SelectionMode="Multiple" 這裡設置一下即可

Multiple Select (MultiSelect) DropDownList with CheckBoxes in ASP.Net using jQuery



Ref:

http://multiple-select.wenzhixin.net.cn/docs/en/methods

jQuery Plugin For Selecting Multiple Elements - Multiple Select
https://www.jqueryscript.net/demo/jQuery-Plugin-For-Selecting-Multiple-Elements-Multiple-Select/
https://www.jqueryscript.net/form/jQuery-Plugin-For-Selecting-Multiple-Elements-Multiple-Select.html

留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header