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<Values> GetChild(int ParientID)
        {
            List<Values> obj=new List<Values>();

            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<dynamic>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%Html.BeginForm(); %>


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

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

    $(document).ready(function () {
        debugger;
        $("#obj_ParientValue").change(function () {

            var Parient = getParient();

            // poor man's validation
            if (Parient == null) {
                alert("Specify a name please!");
                return;
            }

            debugger;

            var jsonSerialized = JSON.stringify(Parient);
            $.ajax({
                type: "POST",
                url: "/home/GetChildJson",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: jsonSerialized,
                success: function (result) {

                    var target = "#obj_ChildValue";
                    if (result) {

                        $(target).find('option').remove().end().append('<option value="0">please select</option>').val('whatever');

                        $(result).each(function () {
                            debugger;
                            console.log(this);
                            var option = $("<option></option>").attr("value", this.Value).text(this.Text);
                            $(target).append(option);
                        });

                    }
                    console.log(result);
                },
                error: function (error) {
                    debugger;
                    alert("There was an error posting the data to the server: " + error.responseText);
                }
            });

        });
    });

    function getParient() {
        var text = $("#obj_ParientValue").val();
        var value = $("#obj_ParientValue").val();
        debugger;
        // poor man's validation
        return (text == "") ? null : { Text: text, Value: 3 };
    }
</script>
<%Html.EndForm(); %>
</asp:Content>

This Is the layout of the page.

You can download the hole sample from Here.