DazManCat
DazManCat

Reputation: 3620

Mapping JSON AJax response to JQuery auto complete

I've been playing around with JQuery autocomplete. Following the example on http://www.asp.net/ajaxlibrary/jquery_mvc_autocomplete.ashx

The autocomplete component shows 2 blank entires (although if I select one option the hidden field I use to store the selected titleID is being populated).

I suspect that I am not mapping the response correctly and that it is something really obvious I am missing but, can't for the life of me spot it.

Controller method.

public ActionResult SearchTitle(string term)
    {
        var results = new List<Models.Title>{ new Models.Title{ Name = "TestResponse1",TitleId=123 }, new Models.Title { Name = "TestResponse2", TitleId=234} };
        return Json(results.ToArray(),JsonRequestBehavior.AllowGet);
    }

View

@using (Html.BeginForm())
{
    <h3>Add a new subscription</h3>
        @Html.TextBox("Name")
        @Html.Hidden("TitleId")
        <input type="submit" value="Find Title" />

}


@Styles.Render("~/Content/themes/base/css")

<script type="text/javascript">
    $("#Name").autocomplete({
        source: '@Url.Action("SearchTitle")',
        dataType: "json",
        messages: { noResults: 'No titles found' },
        select: function (event, ui) {
            $("#TitleId").val(ui.item.TitleId);
        }

    });

</script>  

Can anyone spot what I am doing wrong?


OK following that advice the autocomplete now shows values, however nothing happens when I select an item from the dropdown. Can anyone spot what I have missed?

<script type="text/javascript">
    $("#Name").autocomplete({
        source: '@Url.Action("SearchTitle")',
        dataType: "json",
        messages: { noResults: 'No titles found' },
        focus:function(event,ui){
            $("#Name").val(ui.item.Name);
            return false;
        },
        select: function (event, ui) {
            $("#Name").val(ui.item.Name)
            $("#TitleId").val(ui.item.TitleId);
            return false;
        }
    })
    .data("ui-autocomplete")._renderItem = function (ul, item) {
        return $("<li>")
          .append(item.Name)
          .appendTo(ul)
    };

</script>  

Upvotes: 1

Views: 1708

Answers (1)

Lukas S.
Lukas S.

Reputation: 5758

The data returned by SearchTitle is not a simple list of strings - it's a custom format, and jQuery UI autocomplete doesn't know what values should be displayed in the dropdown. You should take a look at the custom data sample:

http://jqueryui.com/autocomplete/#custom-data

jQuery UI autocomplete will look for a label property to figure out what should be displayed to the user, and a value property (which can be an object, not necessarily a plain string) as the underlying data. You'll need to transform your custom data into this format, either on the server (in SearchTitle, or in a new action method), or on the client (by specifying a function as the source property where you perform this transformation). Here's an example of how you would do this on the client (warning - not tested):

$("#Name").autocomplete({
    source: function( request, response ) {
        $.getJSON( '@Url.Action("SearchTitle")', { term: request.term }, function( data, status, xhr ) {
            var titles = $.map( data, function (title) {
                return {
                    label: title.Name,
                    value: title.TitleId
                };
            });
            response( titles );
        });
    },
    // ...        
});

Upvotes: 2

Related Questions