Mahmoud ElMansy: knowledge meant to be free

Make Cascade Dropdownlist asp.net MVC with Json

We are as programmers needs always to fill Dropdownlist with values or keys selected from other
Dropdownlist we can achieve this by meany ways, in this post i will use
Mvc.net and Json to fill Dropdownlist by values selected from Database .

Let us start.
1) Make new application type asp.net MVC.
2) Put this code in the HomeController .

[HttpGet]
public ActionResult CascadingDropDown()
{
CascadeClass obj= new CascadeClass();

return View(obj);
}
[HttpPost]
public ActionResult CascadingDropDown(CascadeClass obj,FormCollection coll)
{
return View(obj);
}
[HttpPost]
public JsonResult GetChildJson(Values obj)
{
return Json(CascadeViewModel.GetChild(obj.Value), JsonRequestBehavior.AllowGet);
}

3) Make class Named “CascadeViewModel” and put this code inside.

public static List GetChild(int ParientID)
{
List obj=new List();

if (ParientID == 0)
{
obj.Add(new Values() {Text="chield01" ,Value=1});
obj.Add(new Values() { Text = "chield02", Value = 2 });
obj.Add(new Values() { Text = "chield03", Value =3 });
obj.Add(new Values() { Text = "chield04", Value = 4 });
}
else if (ParientID == 1)
{
obj.Add(new Values() { Text = "chield11", Value = 1 });
obj.Add(new Values() { Text = "chield12", Value = 2 });
obj.Add(new Values() { Text = "chield13", Value = 3 });
obj.Add(new Values() { Text = "chield14", Value = 4 });
}
else if (ParientID == 2)
{
obj.Add(new Values() { Text = "chield21", Value = 1 });
obj.Add(new Values() { Text = "chield22", Value = 2 });
obj.Add(new Values() { Text = "chield23", Value = 3 });
obj.Add(new Values() { Text = "chield24", Value = 4 });
}
else
{
obj.Add(new Values() { Text = "chield31", Value = 1 });
obj.Add(new Values() { Text = "chield32", Value = 2 });
obj.Add(new Values() { Text = "chield33", Value = 3 });
obj.Add(new Values() { Text = "chield34", Value = 4 });

}
return obj;
}

4) Make new view named “CascadingDropDown”
And here is the full code of the view.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<%Html.BeginForm(); %>

CascadingDropDown

<% CascadingDropDownJson.Models.CascadeClass obj = (CascadingDropDownJson.Models.CascadeClass)Model; %>
<%:Html.DropDownListFor(gg => obj.ParientValue, new SelectList(obj.ParientList, "Value", "Text"), new { name = "journals" })%>
<%:Html.DropDownListFor(gg => obj.ChildValue, new SelectList(obj.ChildList, "Value", "Text"), new { name = "Issuess" })%>


<%Html.EndForm(); %>

This Is the layout of the page.

You can download the hole sample from Here.