1

like described in the headline i got a little problem getting the jqueryUI autocomplete Widget to work.

It sounds silly but im hanging the whole day getting that thing solved, but i didnt. I`ve developed a few years C# and now trying, since a month or so..., to develop with asp and jquery. Just for showing, I´ve searched the web and especially stackoverflow and tried a lot to getting it run.

Ok here`s the code.

Definition TextBox:

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

The AutoComplete Jquery Script Part:

<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>

The 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();
} 

For the sake of completeness, the 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;
   }

If you need more, please tell me.

The debug lines are outcommented.

If i check the jquery part i get the data i want but it won't be displayed at the txtsearch. And i didn't really understand how that AutoComplete jquerUI Method will display that List, but the coding should be correct.

2
  • What does the response from your web service method look like? (As in the JSON encoded data that is sent to the client) Commented May 30, 2012 at 15:11
  • {"d":[{"__type":"SearchObject","Nr1":"58155","nr2":"E58155","Name":"XX Name","SearchString":"58155 XX Name E58155"}]} - But that`s OK, it was a JavaScript Feature - look at the last Answer, with changing the code structrure a little bit, everything works, really wired. Commented May 31, 2012 at 6:54

3 Answers 3

7

Actually, you could be a victim of a very nasty JavaScript feature called automatic semicolon insertion. The return statement in your success callback / jQuery map function is written wrong.

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

This should be a correct syntax:

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

JavaScript compiler adds an automatic semicolon behind the return statement in the first case, causing it to return nothing / undefined.

This SO question has a very good overview of the rules for this behavior.

Sign up to request clarification or add additional context in comments.

2 Comments

Thats really a very nasty & stinky Feature. That means if you try to get your Code into a nice looking structure(for me it looks good that way ; ) ) that wont work. So after all searching around it works, Thank you very much Miroslav!
Not a problem. Glad I could help.
1

I have autocomplete running using asp.net, c# on .net 4. This is how i do it.

// for .aspx page,

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

// text box, I don't use server side text box here, but I don't see it being an issue for 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;
            }
        }
    }

1 Comment

Thank you - Another interesting approach. I got it to work, the last answer did it, an absolute unnecessary JavaScript Feature causes that Errror.
1

Problem Solved.

It Works, with the help of Miroslav Popovic, i got the thing to work, it was that really useless JavaScript Feature 'automatic semicolon insertion'.

With a little changing the Code structure everything works fine.

Here`s the corrected part:

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

THX - To all that helped

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.