ASP.NET MVC jQuery Autocomplete plug-in using JSON.
This post demonstrate how to use JQuery Autocomplete feature in ASP.NET MVC. In this demo we call the controller Action method to get the data in JSON format and bind it to the text box to accomplish the Autocomplete feature.
Before starting download the js and css file from jQuery Autocomplete plugin and add in the project and follow the steps mention below
Step 1. Add the following code for action method in controller
public
ActionResult StateLookup(string q, int limit)
{
var jsonData = new[]{
new {Code = "AL", Name = "Alabama"},
new {Code = "CA", Name= "Califonia"},
new {Code = "IN", Name = "Indiana"},
new {Code = "MD", Name = "Maryland"},
new {Code = "NJ", Name = "New Jersey"}
};
return Json(jsonData);
}
I have used hardcode JSON list for the state. You can construct the JSON data from database using LINQ.
Step 2. Add the following java script in the view
<script
type="text/javascript">
$(document).ready( function() {
$('#state').autocomplete('<%=Url.Action("StateLookup", "Home") %>', {
dataType: 'json',
parse: function(data) {
var rows = new Array();
for(var i=0; i<data.length; i++){
rows[i] = { data:data[i], value:data[i].Code, result:data[i].Code };
}
return rows;
},
formatItem: function(row, i, n) {
return row.Code + ' - ' + row.Name;
},
width: 300,
mustMatch: true,
});
});

No comments:
Post a Comment