Cascading Drop down with simple JQuery script & JSON (W/o Jquery cascading plugin)


Let’s use an example:
Say I want to list available counties per state. So the the first drop down will be the state drop down, and based on the selection of the state, the second drop down will display available counties for the selected state.

<%= Html.DropDownList("StateID", Model.StateList) %>
<select name="CountyID" id="CountyID"></select>

JS:

$(document).ready(function() {
$("#StateID").change(function() {
var strStateID = "";
strStateID = $(this)[0].value; // get the selected state id
var url = "/MyController/Counties/" + strStateID;
// call controller's action
$.getJSON(url, null, function(data) {
// do something once the data is retrieved
$("#CountyID").empty();
$.each(data, function(index, optionData) {
$("#CountyID").append("<option value='"
+ optionData.CountyID
+ "'>" + optionData.CountyName
+ "</option>");
});
});
})
.change(); // making sure the event runs on initialization for default value
});

Controller:
public JsonResult Counties(int stateid)
{ 

var counties = (from c in db.Counties
where (c.StateId == stateid)
order by c.CountyName
select new { countyid = c.CountyId, CountyName = c.CountyName });

return this.Json(counties);

}

Read full detailed at below reference , Thanks to Johannes Setiabudi for nice help … !!

http://setiabud.blogspot.com/2009/05/cascading-drop-down-with-aspnet-mvc.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s