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.
It works! Thanks!
ReplyDeletenice blog ... it helped me .. thanx
ReplyDeleteMy blog of the day!! thanks!
ReplyDeleteIt works for me.... Thnx
ReplyDeleteWhat application are you using for the screencast? It looks very nice :)
ReplyDeleteNice one boss..well done! :)
ReplyDeleteNice one sir..
ReplyDeletevery nice blog, help me alot
ReplyDeleteAbhimanyu i have dane the same but
ReplyDeleteresponse($.map(data, function (item) {
return { label: item.Country, value: item.Country };
}))
this part not working i got list in data
Response Not Working
ReplyDeletedoesnt work
ReplyDelete__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 );
}
This is my action result. am not getting the value at auto complete text box
ReplyDeletepublic 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);
}
check this....C# Autocomplete Textbox
ReplyDeleteLing
messages: {
ReplyDeletenoResults: "", results: ""
}
remove this code to solve the problem with JqueryUI
Hi,
ReplyDeletehow am not able to call javascript function while selecting the suggestion in autocomplete.any one can help me out on this....advance thanks..
Hi,
ReplyDeleteam not able to call the javascript function while selecting the suggestion in autocomplete.can any one help me on this...thanks in advance..
Is there any possibility without bullets
ReplyDeleteI 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?
ReplyDeleteAwesome
ReplyDeleteThanks :)
ReplyDeleteNot 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.
ReplyDeleteIt helps a lot......thanks
ReplyDeleteThanks a lot,
ReplyDeleteIt helped me much. Thanks again.