Sunday, 26 October 2014

Creating Simple Cascading DropDownList In MVC 4 Using Razor

This article shows how to create a Cascading Dropdownlist.

Use JSON with razor syntax.

CascadingDropDown enables a common scenario in which the contents of one list depends on the selection of another list and does so without having to embed the entire data set in the page or transfer it to the client at all.

The main purpose is to reduce Postbacks.

Let's start.

Srep 1: Create a project then select Web from above Menu in left
Step 2: Select ASP.NET MVC 4 Web Application.

MVC 4 Web Application

Internet Application

And name it Cascadingdropdownlist.

Step 3: After creating the application we will add a Controller to the page.

For adding the Controller right-click on the Controller Folder and select Add inside add Select Controller.

Adding Controller

Controller

And I am naming the Contoller CustomerFeedbackController.cs.

Step 4: After adding the Controller to the application I am now just adding a new action result and naming it LoadCountries.
public ActionResult LoadCountries()
{
     List<SelectListItem> li = new List<SelectListItem>();
     li.Add(new SelectListItem { Text = "Select", Value = "0" });
     li.Add(new SelectListItem { Text = "India", Value = "1" });
     li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
     li.Add(new SelectListItem { Text = "China", Value = "3" });
     li.Add(new SelectListItem { Text = "Austrila", Value = "4" });
     li.Add(new SelectListItem { Text = "USA", Value = "5" });
     li.Add(new SelectListItem { Text = "UK", Value = "6" });
     ViewData["country"] = li;
     return View();
}
In this I created a Generic List and in the list I am adding an item to it.

After adding I am storing it in ViewData for passing to the view.

Step 5: For adding the View to LoadCountries rigtht-click on the loadCountries and select Add View.

Add View

Add a click on the Add Button. Add Razor Syntax to the Begin Form.

@using (Html.BeginForm())
{
}

Step 6: Add a Dropdown list with Name of Countries and Binding ViewData to the Dropdownlist.
@using (Html.BeginForm())
{
    @Html.DropDownList("Countries", ViewData["country"as List<SelectListItem>)
}
Now just run the application and check how it is output.

just run application

The preceding was a simple example of how to bind a list to a Dropdownlist in MVC.

Now we will be doing a Cascading Dropdown Demo. For that we would be writing a JSON script and JSON method.

And add two DropDownLists with an empty Datasource.

Step 7:
  1. State DropDownList

    @Html.DropDownList("State"new SelectList(string.Empty, "Value""Text"), "Please select a State"new { style = "width:250px", @class = "dropdown1" })
     
  2. City DropDownList

    @Html.DropDownList("city"new SelectList(string.Empty, "Value""Text"), "Please select a city"new { style = "width:250px", @class = "dropdown1" })
Now we have added two DropDownLists.

Here is a Snapshot of the View:

Snapshot of View

Step 8: Further we will be adding a method for the JSON and a script for JSON for the States.

Just below I have added the method for JSON.

And also you will see the method for JSON is taking an input parameter, id (this is the id of the Country Dropdownlist that I created).

The Script for JSON will be called when the Country Dropdownlist is selected.
public JsonResult GetStates(string id)
{
    List<SelectListItem> states = new List<SelectListItem>();
    switch (id)
    {
        case "1":
             states.Add(new SelectListItem { Text = "Select", Value = "0" });
             states.Add(new SelectListItem { Text = "ANDAMAN & NIKOBAR ISLANDS", Value = "1" });
             states.Add(new SelectListItem { Text = "ANDHRA PRADESH", Value = "2" });
             states.Add(new SelectListItem { Text = "ARUNACHAL PRADESH", Value = "3" });
             states.Add(new SelectListItem { Text = "ASSAM", Value = "4" });
             states.Add(new SelectListItem { Text = "BIHAR", Value = "5" });
             states.Add(new SelectListItem { Text = "CHANDIGARH", Value = "6" });
             states.Add(new SelectListItem { Text = "CHHATTISGARH", Value = "7" });
             states.Add(new SelectListItem { Text = "DADRA & NAGAR HAVELI", Value = "8" });
             states.Add(new SelectListItem { Text = "DAMAN & DIU", Value = "9" });
             states.Add(new SelectListItem { Text = "GOA", Value = "10" });
             states.Add(new SelectListItem { Text = "GUJARAT", Value = "11" });
             states.Add(new SelectListItem { Text = "HARYANA", Value = "12" });
             states.Add(new SelectListItem { Text = "HIMACHAL PRADESH", Value = "13" });
             states.Add(new SelectListItem { Text = "JAMMU & KASHMIR", Value = "14" });
              states.Add(new SelectListItem { Text = "JHARKHAND", Value = "15" });
              states.Add(new SelectListItem { Text = "KARNATAKA", Value = "16" });
              states.Add(new SelectListItem { Text = "KERALA", Value = "17" });
              states.Add(new SelectListItem { Text = "LAKSHADWEEP", Value = "18" });
              states.Add(new SelectListItem { Text = "MADHYA PRADESH", Value = "19" });
              states.Add(new SelectListItem { Text = "MAHARASHTRA", Value = "20" });
              states.Add(new SelectListItem { Text = "MANIPUR", Value = "21" });
              states.Add(new SelectListItem { Text = "MEGHALAYA", Value = "22" });
              states.Add(new SelectListItem { Text = "MIZORAM", Value = "23" });
              states.Add(new SelectListItem { Text = "NAGALAND", Value = "24" });
              states.Add(new SelectListItem { Text = "NCT OF DELHI", Value = "25" });
              states.Add(new SelectListItem { Text = "ORISSA", Value = "26" });
              states.Add(new SelectListItem { Text = "PUDUCHERRY", Value = "27" });
               states.Add(new SelectListItem { Text = "PUNJAB", Value = "28" });
               states.Add(new SelectListItem { Text = "RAJASTHAN", Value = "29" });
               states.Add(new SelectListItem { Text = "SIKKIM", Value = "30" });
               states.Add(new SelectListItem { Text = "TAMIL NADU", Value = "31" });
               states.Add(new SelectListItem { Text = "TRIPURA", Value = "32" });
               states.Add(new SelectListItem { Text = "UTTAR PRADESH", Value = "33" });
               states.Add(new SelectListItem { Text = "UTTARAKHAND", Value = "34" });
               states.Add(new SelectListItem { Text = "WEST BENGAL", Value = "35" });
            break;
               case "UK":
           break;
            case "India":
          break;
    }
    return Json(new SelectList(states, "Value""Text"));
}
Step 9: After creating the method for JSON I just wrote a script for JSON.
<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#Country").change(function () {
            $("#State").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetStates")'// we are calling json method

                dataType: 'json',

                data: { id: $("#Country").val() }, 
               // here we are get value of selected country and passing same value
                  as inputto json method GetStates.

                success: function (states) {
                    // states contains the JSON formatted list
                    // of states passed from the controller

                    $.each(states, function (i, state) {
                    $("#State").append('<option value="' + state.Value + '">' +  
                         state.Text + '</option>');                                                                                                
                    // here we are adding option for States

                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });
</script>
Step 10:

We have just now bound States from Country. We will now bind city from States.

in the same manner I created a method for JSON for binding the City.
public JsonResult GetCity(string id)
{
            List<SelectListItem> City = new List<SelectListItem>();
            switch (id)
            {
                case "20":
                    City.Add(new SelectListItem { Text = "Select", Value = "0" });
                    City.Add(new SelectListItem { Text = "MUMBAI", Value = "1" });
                    City.Add(new SelectListItem { Text = "PUNE", Value = "2" });
                    City.Add(new SelectListItem { Text = "KOLHAPUR", Value = "3" });
                    City.Add(new SelectListItem { Text = "RATNAGIRI", Value = "4" });
                    City.Add(new SelectListItem { Text = "NAGPUR", Value = "5" });
                    City.Add(new SelectListItem { Text = "JALGAON", Value = "6" });
                    break;
            }

            return Json(new SelectList(City, "Value""Text"));
}
Step 11:  And also wrote a script for JSON that wil be active when you select States.
<script type="text/javascript">
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#State").change(function () {
            $("#city").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetCity")',
                dataType: 'json',
                data: { id: $("#State").val() },
                success: function (citys) {
                    // states contains the JSON formatted list
                    // of states passed from the controller
                    $.each(citys, function (i, city) {
                        $("#city").append('<option value="'
+ city.Value + '">'
+ city.Text + '</option>');
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });
</script> 
Final step

Countries Dropdown snapshot.

Dropdown

States Dropdown snapshot.

States Dropdown

City Dropdown snapshot.

City Dropdown

And featching data a post here is a snapshot.

Featching Data
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/

No comments:

Post a Comment