簡體   English   中英

asp.net jqueryUI自動完成

[英]asp.NET jqueryUI autocomplete

就像標題中所述,我在使jqueryUI自動完成小部件工作時遇到了一些問題。

聽起來很傻,但是我m hanging the whole day getting that thing solved, but i didn 我已經開發了幾年的C#,現在,從一個月左右開始,就嘗試使用ASP和JQuery進行開發。 只是為了展示,我搜索了網絡,尤其是stackoverflow,並嘗試了很多以使其運行。

好的,這里是代碼。

定義文本框:

 <asp:TextBox ID="txtSearchbox"
                    style="float:left;padding:5px 1px 5px 1px;" runat="server" >
 </asp:TextBox>

AutoComplete Jquery腳本部分:

<script type="text/javascript">

    $(document).ready(function () {
        $('#txtSearchbox').autocomplete( {
         source: function (request, response) {
                    //console.log(request.term);
             $.ajax
             ({
                 url: "AutoComplete.asmx/GetSearchInfo",
                 data: "{ 'prefixText': '" + request.term + "' }",
                 dataType: "json",
                 type: "POST",
                 contentType: "application/json; charset=utf-8",
                 dataFilter: function (data) {
                     //console.log(data.toString());
                     //alert(data.toString());
                     return data;
                 },
                 success: function (data) {
                     // console.log(data.d.toString());
                     response($.map(data.d, function (item) {
                         // console.log(item.Isin)
                         // console.log(item.Name)
                         return
                         {
                             label: item.Name.toString()
                             value: item.Name.toString()
                         }
                     }));
                },
                 error: function (XMLHttpRequest, textStatus, errorThrown) {
                     alert(textStatus);
                 }
             });
         },
         minLength: 2
         });
    });

</script>

AutoComplet.asmx:

[WebMethod]
public List<SearchObject> GetSearchInfo(string prefixText) 
{
    var seo = new SearchObject();
    var getSeo = staticList.getSEOlist().Where(str => str.SearchString.ToLower().Contains(prefixText.ToLower()));

    return getSeo.ToList();
} 

為了完整起見,CSS:

    /*AutoComplete flyout */
.autocomplete_completionListElement
{
    margin:0px!important;
    background-color:#ffffff;
    color:windowtext;
    border:buttonshadow;
    border-width:1px;
    border-style:solid;
    cursor:'default';
    overflow:auto;
    height:200px;
    font-family:Tahoma;
    font-size:small;
    text-align:left;
    list-style-type:none;
    padding: 5px 5px 5px 5px;
    }

/* AutoComplete highlighted item */
.autocomplete_highlightedListItem
{
    background-color:#ffff99 ;
    color:black;
    padding:0px;
    }

    /* AutoComplete item */
.autocomplete_listItem
{
    background-color:window;
    color:windowtext;
    padding:0px;
   }

如果您需要更多,請告訴我。

調試行過時。

如果我檢查jquery部分,我會得到我想要的數據,但不會在txtsearch中顯示。 而且我並不真正了解該AutoComplete jquerUI方法將如何顯示該列表,但是編碼應該是正確的。

實際上,您可能是非常討厭的JavaScript功能(稱為自動分號插入)的受害者。 成功回調/ jQuery映射函數中的return語句寫錯了。

return
{
    label: item.Name.toString()
    value: item.Name.toString()
}

這應該是正確的語法:

return {
    label: item.Name.toString()
    value: item.Name.toString()
}

JavaScript編譯器在第一種情況下會在return語句后添加一個自動分號,從而使其不返回任何內容/未定義。

這個SO問題很好地概述了這種行為的規則。

我使用asp.net,.net 4上的c#運行自動完成功能。這就是我的方法。

//對於.aspx頁,

   <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference Path="/PathToServiceHere/AutoComplete.svc" />            
    </Services>
</asp:ScriptManager>

//文本框,這里我不使用服務器端文本框,但我認為這不是JQuery的問題

  <input id="ModelBox" type="text" style="width: 158px;" />

// jQuery

     $(function () {
            $("#ModelBox").autocomplete({
                minLength: 0,
                delay: 0,
                cache: true,
                source: function (req, addToList) {

                    var popList = new GetAutoCompleteService.GetAutoComplete();
                    popList.GetModels(req.term, function (model) {

                        var listItems = [];
                        if (model.length > 0) {
                            for (var key = 0; key < model.length; key++) {
                                listItems.push(model[key].Model);
                            }
                        } else {
                            listItems.push("No Matching Model.");
                        }
                        addToList(listItems);
                    }, function onError() {
                    });
                }
            });

            $("#ModelBox").click(function () {
                // close if already visible
                if ($("#ModelBox").autocomplete("widget").is(":visible")) {
                    $("#ModelBox").autocomplete("close");
                    return;
                }

                // work around a bug (likely same cause as #5265)
                $(this).blur();

                // pass empty string as value to search for, displaying all results
                $("#ModelBox").autocomplete("search", "");
                $("#ModelBox").focus();
            });
        });

// AutoComplete.svc

  namespace autocomplete.Service
    {
        using System.Collections.Generic;
        using System.Linq;

        using System.ServiceModel;
        using System.ServiceModel.Activation;

        using System.Data;

        [ServiceContract(Namespace = "GetAutoCompleteService")]
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        public class GetAutoComplete
        {

            [OperationContract]
            public List<Models> GetModels(string model)
            {

               // Data access here to retrieve data for autocomplete box then convert to list

    // or however you get the data into list format
                List<Models> List = dataJustPulled.ToList(); 
                return List;
            }
        }
    }

問題解決了。

它的工作原理是在Miroslav Popovic的幫助下完成的,那是真正沒用的JavaScript功能“自動分號插入”。

稍稍更改一下代碼結構,一切都可以正常工作。

這是更正的部分:

return{
       label: item.Name.toString(),
       value: item.Name.toString()
}

THX-對所有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM