CascadingDropDown in ASP.NET MVC

1. Download CascadingDropDown jQuery Plugin

2. Put file jquery.cascadingDropDown.js in ~\Scripts

3. Add the following line of code in ~\App_Start\BundleConfig.cs

    bundles.Add(new ScriptBundle("~/bundles/jqueryplugin").Include(
        "~/Scripts/jquery.cascadingDropDown.js"));

4. Create a View Model for the Cascading DropDown Select Lists and the selected values

public class CascadingDropDownViewModel
{
    public SelectList AreaSelectList { get; set; }

    public SelectList DistrictSelectList { get; set; }

    [Display(Name = "Area")]
    public Area Area { get; set; }

    [Display(Name = "District")]
    public District District { get; set; }
}

5. Create a Controller for populating the View Model

public ActionResult CascadingDropDown()
{
    CascadingDropDownViewModel model = new CascadingDropDownViewModel();
    model.AreaSelectList = new SelectList(_entities.Areas, "AreaId", "Name");
    model.DistrictSelectList = new SelectList(Enumerable.Empty(), "DistrictId", "Name");

    return View(model);
}

6. Create a View to show the Cascading DropDown

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.LabelFor(m => m.Area) :
    @Html.DropDownListFor(m => m.Area, Model.AreaSelectList, "-- Please Select --")
    @Html.ValidationMessageFor(m => m.Area)


    @Html.LabelFor(m => m.District) :
    @Html.DropDownListFor(m => m.District, Model.DistrictSelectList)
    @Html.ValidationMessageFor(m => m.District)


    <button type="submit">Submit</button>
}

@section scripts{
<script type="text/javascript">// <![CDATA[
        $(document).ready(function () {
            $("#District").CascadingDropDown("#Area", "/Ajax/DistrictCascadingDropDown",
            {
                promptText: "-- Please Select --",
                postData: function () {
                    return { areaId: $("#Area").val() };
                }
            });
        });

// ]]></script>
}

7. Create a dedicated Controller AjaxController and an Action method DistrictCascadingDropDown

public ActionResult DistrictCascadingDropDown(int areaId)
{
	var query = from d in _entities.Districts
				where d.AreaId == areaId
				select d;

	SelectList selectList = new SelectList(query, "DistrictId", "Name");

	return Json(selectList);
}

References

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