Cascading DropDownList Example Using JSONResult in ASP.NET MVC

This article shows you how to add values of JSONResult to cascading DropDownList. For this I will be using jQuery.Ajax request which will call Controller action method which return JSON object.

Create a new application with default settings for MVC environment. You will add corresponding ActionResult and Views.

Follow below steps to bind Category DropDownList and cascading Sub Category DropDownlist.


Bind Category DropDownList

In this step you will bind parent DropDownList that is Category. Which is like parent list of values.

Open HomeController from Controllers folder and add below Action method.


public ActionResult DisplayCategories()
{
    List<SelectListItem> items = new List<SelectListItem>();

    items.Add(new SelectListItem{Text="Select Category",
                Value="0", Selected=true });

    items.Add(new SelectListItem{Text="Beverage",Value="1"});

    items.Add(new SelectListItem{Text="Condiment",Value="2"});

    items.Add(new SelectListItem{Text="Confection",Value="3"});

    items.Add(new SelectListItem{Text="Dairy",Value="4"});

    items.Add(new SelectListItem{Text="Grains",Value="5"});

    items.Add(new SelectListItem{Text="Meat",Value="6"});

    items.Add(new SelectListItem{Text="Produce",Value="7"});

    items.Add(new SelectListItem{Text="Seafood",Value="8"});

    ViewBag.CategoryType = items;

    return View();
}
    
            

Categories from Northwind Database are added to list and assign it to ViewBag property. See more details on binding MVC DropDownlist

Add below View to display Categories. Right click in DisplayCategories action method and select Add View. It adds a new View under Views -> Home folder.

Open DisplayCategories.cshtml created in previous step. Add below html code which add required DropDownList and its bindings.


@{
    ViewBag.Title = 
        "Cascading DropDownList example in ASP.NET MVC 
                - dotnetmentors.com";
}

<h2<Cascading DropDownList example in ASP.NET MVC 
               - dotnetmentors.com</h2<
@using (Html.BeginForm("CategoryChosen", "Home",
                FormMethod.Get))
{
    <table cellspacing="2" cellpadding="2">
        <tr>
            <td>
                Category Type :
            </td>
            <td>
               @Html.DropDownList("CategoryType")     
            </td>
        </tr>
        
        <tr>
            <td>
                Sub Category:
            </td>
            <td>
                @Html.DropDownList("SubCategory", 
                    new SelectList(string.Empty,
                         "Value", "Text"),
                    "Please select a Sub Category", 
                    new { style = "width:250px" })
            </td>
        </tr>
    </table>    
}
    
            

Controller Action method to return JSON

In this step we will write a action method to return JSON object. This JSON object values will be added to Cascading DropDownList that is SubCategory.

This action method is getting called using jQuery.Ajax() method on change of Category (parent) DropDownList.

Open HomeController and add below Action method.


public JsonResult GetSubCategories(string id)
{
List<SelectListItem> subCategories = 
            new List<SelectListItem>();

subCat.Add(new SelectListItem{Text="Select",
            Value="0"});

switch (id)
{
    case "1":
    subCat.Add(new SelectListItem{Text="Coffee",Value="1"});
    subCat.Add(new SelectListItem{Text="Energy",Value="2"});
    subCat.Add(new SelectListItem{Text="Tea",Value="3"});
    subCat.Add(new SelectListItem{Text="Cold",Value="4"});
    break;
    case "2":
    subCat.Add(new SelectListItem{Text="Garlic",Value="1" });
    subCat.Add(new SelectListItem{Text="Pickles",Value="2" });
    subCat.Add(new SelectListItem{Text="Raita",Value="3" });
    subCat.Add(new SelectListItem{Text="Sauce",Value="4" });
    break;
    case "3":
    subCat.Add(new SelectListItem{Text="Desserts",Value="1"});
    subCat.Add(new SelectListItem{Text="Sweet",Value="2" });                    
    break;
    case "4":
    subCat.Add(new SelectListItem{Text="Cheese",Value="1"});                    
    break;
    case "5":
    subCat.Add(new SelectListItem{Text="Crackers",Value="1"});
    subCat.Add(new SelectListItem{Text="Pasta",Value="2"});
    break;
    case "6":
    subCat.Add(new SelectListItem{Text="Prepared",Value="1"});                    
    break;
    case "7":
    subCat.Add(new SelectListItem{Text="Dried Fr",Value="1"});                    
    break;
    case "8":
    subCat.Add(new SelectListItem{Text="Fish",Value="1"});
    subCat.Add(new SelectListItem{Text="Crab",Value="2"});
    break;
    default:
    subCat.Add(new SelectListItem{Text="Coffee",Value="1"});    
    subCat.Add(new SelectListItem{Text="Tea",Value="3"});
    subCat.Add(new SelectListItem{Text="Colddrinks",Value="4"});
    break;
}            

return Json(new SelectList(subCat,
                "Value", "Text"));
}

    
            

jQuery.Ajax to call Controller action

This step will create a simple jQuery.Ajax call. It calls to HomeController action method which returns JSON object.

The values of JSON object return to ajax call will be added to Cascading DropDownList in success part of jQuery.Ajax() call.

Open DisplayCategories.cshtml view and at the end of existing HTML code add below script code.

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {

$("#CategoryType").change(function () {

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

    $.ajax({

        type: 'POST',

        url: '@Url.Action("GetSubCategories")', 
        dataType: 'json',
        data: { id: $("#CategoryType").val() },
        success: function (subcategories) {

            $.each(subcategories, function (i, subcategory) {

                $("#SubCategory").append('<option value="' 
                    + subcategory.Value + '">' +
                    subcategory.Text + '</option>');
            });
        },
        error: function (ex) {
            alert('Failed to retrieve Sub Categories : ' + ex);
        }
    });
    return false;
})
});
</script>
            

Your cascading DropDownList is ready. It should display below output.

ASP.NET MVC Cascading DropDownList example

Download source code.

Speak your mind :
Leave a comment for this article on dotnetbloogers.com