Ask your question here : ASP.NET or MVC | C# | Windows Phone
Microsoft Technology Journals by Abhimanyu K Vatsa
HOME ABOUT RAZOR BOOK MVC ASP.NET JQUERY C# VIDEOS EBOOK ARCHIVE

14 Feb 2013

jQuery UI Autocomplete with JSON in MVC 4

In the last post jQuery Ajax GET and POST calls to Controller's Method in MVC we saw an example on ‘GET call with parameter to Controller’s Method which will return JSON data’ (in case you missed, go and read that before continuing here), let me put the screenshot here.



So, in this post I’m going to continue my talk to enhance that functionality and allow autocomplete feature in that textbox. Means, when user starts typing in the textbox, autocomplete should appear and allow the user to select from it. Here is the running screenshot.


Please find the code snippets I’m using on view page.

<p>
    Enter country name @Html.TextBox("Country")
    <input type="submit" id="GetCustomers" value="Submit"/>
</p>

<span id="rData"></span>

@*Don't repeat if 'jquery-1.8.2.min.js' library already referenced in _Layout.cshtml*@
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery-ui-1.9.2.min.js"></script>
@Styles.Render("~/Content/themes/base/css")

<script type="text/javascript">
    $(document).ready(function () {
        $("#Country").autocomplete({
            source: function(request,response) {
                $.ajax({
                    url: "/Home/AutoCompleteCountry",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Country, value: item.Country };
                        }))

                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>

In above code, I have created a textbox using Razor syntax also placed the references of required libraries to run jQuery Autocomplete. I have attached the autocomplete functionality with ‘Country’ ID and then making an Ajax call to Home controller’s AutoCompleteCountry method with parameter term: request.term, this method will return JSON data. The JSON data returned by the AutoCompleteCountry method will be used to create the autocomplete unordered list and displayed to user.

Now, here is the code of AutoCompleteCountry method that will accept a parameter and return the matching JSON data.

public JsonResult AutoCompleteCountry(string term)
{
    var result = (from r in db.Customers
                    where r.Country.ToLower().Contains(term.ToLower())
                    select new { r.Country }).Distinct();
    return Json(result, JsonRequestBehavior.AllowGet);
}

As you can see, I’m using linq query to filter the country. See how Autocomplete and Ajax sending the request to AutoCompleteCountry method on each char typing. I’m using Firebug extension installed in Chrome.


Hope this helps.

Comment using Google Services (14 comments):

  1. My blog of the day!! thanks!

    ReplyDelete
  2. What application are you using for the screencast? It looks very nice :)

    ReplyDelete
  3. Nice one boss..well done! :)

    ReplyDelete
  4. very nice blog, help me alot

    ReplyDelete
  5. Abhimanyu i have dane the same but
    response($.map(data, function (item) {
    return { label: item.Country, value: item.Country };
    }))
    this part not working i got list in data

    ReplyDelete
  6. doesnt work
    __response: function( content ) {
    var message;
    this._superApply( arguments );
    if ( this.options.disabled || this.cancelSearch ) {
    return;
    }
    if ( content && content.length ) {
    message = this.options.messages.results( content.length );
    } else {
    message = this.options.messages.noResults;
    }
    this.liveRegion.text( message );
    }

    ReplyDelete
  7. This is my action result. am not getting the value at auto complete text box

    public JsonResult GetSCSrviceName(string item)
    {

    String results = String.Empty;

    SqlParameters inputParams = new SqlParameters();
    inputParams.query = String.Format(Queries.SC_SERVICE_NAME, helper.GetDBPrefix());
    // inputParams.AddParam("1", cntry, OdbcType.Char);

    using (DataSet ds = helper.PopulateDS(inputParams))
    {
    results = COMMHELPERS.buildColumnDataString(ds, ",", 0, 0);
    }

    JsonResult jsonResult = COMMHELPERS.ConvertDelimitedStringToJson(results, ',');

    return jsonResult;
    //return this.Json(results.Where(t => t.StartsWith(term)), JsonRequestBehavior.AllowGet);

    //return Json(jsonResult, JsonRequestBehavior.AllowGet);
    }

    ReplyDelete