2012年10月18日 星期四

{JQuery} Autocomplete 進階應用-text、value值不同(像DropdownList)

autocomplete.aspx :
$("#<%=Txt.ClientID %>").autocomplete('Datasource.aspx', {
                noCache: true,
                lineSeparator: ",",//設定基準為Datasource.aspx中紅色資料連接符號
                //當資料被選擇時
                onItemSelect: findValue,
                onFindValue: findValue,
                //擴充參數給Datasource.aspx
                extraParams: {
                    MPSNo: function () {
                        return $('#<%=TxtVersionNo.ClientID%>').val();
                    }
                }
            });


  function findValue(li) {

                if (li == null) {
                    document.getElementById('<%=TxtItemName.ClientID %>').innerText = '';
                    document.getElementById('<%=TxtItemSpec.ClientID %>').innerText = '';
                }
                else {
                    document.getElementById('<%=TxtItemName.ClientID %>').innerText = li.extra[0];
                    document.getElementById('<%=TxtItemSpec.ClientID %>').innerText = li.extra[1];
                }
            }

Datasource.aspx:
 protected void Page_Load(object sender, EventArgs e)
    {

        var query = "";
        var mpsNo = "";
        if (!string.IsNullOrEmpty(Request.QueryString["q"]))
            query = Request.QueryString["q"].ToUpper();
        if (!string.IsNullOrEmpty(Request.QueryString["MPSNo"]))
            mpsNo = Request.QueryString["MPSNo"];
        var modelList = new PMOperator().ReadPNAuotcompleteDataSource(query, mpsNo).Take(10).ToArray();

        var count = modelList.Count();
        string[] str = new string[count];
        for (int i = 0; i < count; i++)
        {
            if (i == count - 1)
            str[i] = string.Format("{0}|{1}|{2}", modelList[i].PN, modelList[i].PNName, modelList[i].PNSpec);
            else
            {
                str[i] = string.Format("{0}|{1}|{2},", modelList[i].PN, modelList[i].PNName, modelList[i].PNSpec);
            }
        }
        Response.Write(string.Join(Environment.NewLine, str));
    }


PS.
當使用extraParams屬性擴充參數時,autocomplete.js對下列的寫法,會產生問題
MPSNo: function () {
                        return $('#<%=TxtVersionNo.ClientID%>').val();
需將autocomplete.js檔中makeUrl(q) function 修改下段程式碼 (主要是紅字部分):

    function makeUrl(q) {
        var url = options.url + "?q=" + escape(q);
        $.each(options.extraParams, function (key, param) {

            url += "&" + key + "=" + (typeof param == "function" ? param() : param);

        });
        return url;
    };


參考資料:
http://forums.asp.net/t/1830016.aspx/1
http://blog.darkthread.net/post-2009-07-10-jquery-autocomplete-sample.aspx
http://jsgears.com/viewthread.php?tid=114&extra=&page=1

API:
http://api.jqueryui.com/autocomplete/#entry-examples