Tuesday, October 19, 2010

MVC2 Master-Child Dropdown

Scenario:
Past month I got a chance to work on MVC 2 project. While there is lot of tutorial available but a real project always have its own learning.

One of the requirement was to have parent-child drop down for Country-State information. State Drop down will be hidden until Country is selected.

Assumptions:
1. Country is the master drop down
2. State drop down will be child drop down and is wrapped in div 'StateArea'
3. On selection of Country , State drop down should get values.
4. View Model class is 'AssociatedViewModel'

Solution: JQuery was the solution. JQuery will make a ajax call to the GetStates() action in Controller to get all the states for selcted country.

View ( Script ):

   <script language="javascript" type="text/javascript">

window.onload = function () {

// Load the form values collection in variable
var frmCollection = $(":input");

$('#CountryID').change(function (e) {

if ($('#CountryID').val() == 0)
{
$("#StateArea").hide(); // Hide the div containing state drop down

}
else
{
$.ajax({
url: "GetStates",
data: frmCollection,
type: "GET",
datatype: "json",
success: function (result) {

$("#StateArea").show(); // Show the div containing state drop down

$("#State").empty();

$("#State").append("<option selected='true'>Select State</option>");

$.each(result, function (i, item)
{
$("#State").append("<option value='" + item.Value + "'>" + item.Text + "</option>");
});
},
error: function (result) {
}
});
}
});
</script>
View ( View HTML ):
    <% Html.EnableClientValidation(); %>
<% using (Html.BeginForm())
{%>

<fieldset>
<table> <tr>
<th>
<b>Category Of Recommendation : </b>
</th>
<th>
<%= Html.DropDownListFor(model => model.Country, Model.Countries,
"Select Country", new { Title = "Country", style = "width:auto" })%>

</th>
</tr>
<tr id="specificRecommendationArea">
<th>
<b>Specific Recommendation : </b>
</th>
<th>
<%= Html.DropDownListFor(model => model.State , Model.States ,
"Select States", new { Title = "States", style = "width:auto" })%>

</th>
</tr>
</table>
</fieldset>
<%} %>
Controller:
  public ActionResult GetSpecificRecommendations(AssociatedViewModel viewModel)
{
SomeDataServiceClient client = new SomeDataServiceClient();

viewModel.States = new SelectList(wcfclient.GetAllStatesByCountry(viewModel.Country.Value), "State", "Description");

return Json(viewModel.States, JsonRequestBehavior.AllowGet);
}
Article:

0 comments: