Dotnet 3.5 interview questions and answers Headline Animator

Tuesday, September 22, 2009

ASP.NET MVC jQuery Autocomplete plug-in using JSON.

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,

});

});

</script>

Here, I specify that the rows in the drop down will have the state "Code - Name" format, and that the value that will be put in the textbox is the Code property of the selected item. This is done with the value property of the rows array.

Step 2. Add the HTML Text box

<%= Html.TextBox("state")%>

Complie the application and run it. To get this running, don't forget to include the required javascript files and the css to style the autocomplete drop down.

No comments:

Post a Comment