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.

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
  8. messages: {
    noResults: "", results: ""
    }

    remove this code to solve the problem with JqueryUI

    ReplyDelete
  9. Hi,
    how am not able to call javascript function while selecting the suggestion in autocomplete.any one can help me out on this....advance thanks..

    ReplyDelete
  10. Hi,
    am not able to call the javascript function while selecting the suggestion in autocomplete.can any one help me on this...thanks in advance..

    ReplyDelete
  11. Is there any possibility without bullets

    ReplyDelete
  12. I would want to know if how i would get the corresponding id of each country and put that id in one of the input fields in the form. Is it possible?

    ReplyDelete
  13. Not working for me. In controller I have method AutoComplete which have one input string parameter (term). If I input something in my textbox field in html, a have get that value for input parameter and my LINQ query return list value from table in my database. But, autocomplete is not working. In my textfield in html I have nothing. Plz help. Thanks.

    ReplyDelete
  14. Thanks a lot,
    It helped me much. Thanks again.

    ReplyDelete

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System