Friday, April 8, 2016

Cascading DropDowns in Asp.Net MVC

Here I am going to show Cascading DropDown Lists for Country, State and City in MVC using EntityFrame Work and Linq

Here I am using Visual Studio 2015 with MVC 5 and EntityFramework 6

OutPut :




  • To Create Database with Tables see This Post
  • Now create New Project from VS 2015
  • Add ADO.Net Entity Data Model into Models Folder as shown Below

  • Now go to HomeController and it looks as shown below.
HomeController:

using Country_State_City_Cascading.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Country_State_City_Cascading.Controllers
{
    public class HomeController : Controller
    {
        MVCDBEntities entities = new MVCDBEntities();
        public ActionResult Index()
        {
            ViewBag.Country = entities.Countries.ToList();
            ViewBag.State = new SelectList(entities.States
                            .Where(c => c.ID == 0), "ID""StateName").ToList();
            ViewBag.City = new SelectList(entities.Cities
                            .Where(c => c.ID == 0), "ID""CityName").ToList();
            return View();
        }

        public JsonResult LoadStatesByCountryID(string CountryID, string TempData)
        {
            if (HttpContext.Request.IsAjaxRequest() && CountryID != "")
            {
                int CntryID = Convert.ToInt32(CountryID);
                var StatesData = entities.States
                                 .Where(c => c.CountryID == CntryID).ToList()
                                 .Select(m => new SelectListItem()
                {
                    Text = m.StateName,
                    Value = m.ID.ToString()
                });
                return Json(StatesData, JsonRequestBehavior.AllowGet);
            }
            return null;
        }

        //[AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadCitiesByStateID(string StateID)
        {
            if (HttpContext.Request.IsAjaxRequest() && StateID != "")
            {
                int StID = Convert.ToInt32(StateID);
                var CitisData = entities.Cities
                                .Where(m => m.StateID == StID).ToList()
                                .Select(c => new SelectListItem()
                {
                    Text = c.CityName.ToString(),
                    Value = c.ID.ToString(),
                });
                return Json(CitisData, JsonRequestBehavior.AllowGet);
            }
            return null;
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}


Index.cshtml:

@model Country_State_City_Cascading.Models.MVCDBEntities
@{
    ViewBag.Title = "Home Page";
}
<h3>Cascading DropDownList</h3><br />
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
    $(document).ready(function () {
        $("[id$=ddlCountry]").change(function () {
            var CountryID = $(this).val();
            var select = $("#ddlState");
            if (CountryID != "") {
                $.getJSON("../Home/LoadStatesByCountryID", { CountryID: CountryID },
                    function (StatesData) {
                        select.removeAttr('disabled');
                        select.empty();
                        select.append($('<option/>', { value: 0, text: "-- Select State --" }));
                        $.each(StatesData, function (index, itemData) {
                            select.append($('<option/>',
                                {
                                    value: itemData.Value,
                                    text: itemData.Text
                                }));
                        });
                    });
            }
            else {
                select.attr('disabled''disabled');
                select.val(0);
                var State = $("#ddlCity");
                State.attr('disabled''disabled');
                State.val(0);
            }
        });
        $("#ddlState").change(function () {
            var StateID = $(this).val();
            var select = $("#ddlCity");
            if (StateID != 0) {
                $.getJSON("../Home/LoadCitiesByStateID", { StateID: StateID },
                    function (CitiesData) {
                        select.removeAttr('disabled');
                        select.empty();
                        select.append($('<option/>', { value: 0, text: "-- Select City --" }));
                        $.each(CitiesData, function (index, itemData) {
                            select.append($('<option/>',
                                {
                                    value: itemData.Value,
                                    text: itemData.Text
                                }));
                        });
                    });
            }
            else {
                select.attr('disabled''disabled');
                select.val(0);
            }
        });
    });
</script>
<p>
    <table>
        <tr>
            <td>
                Country
            </td>
            <td>
                : @Html.DropDownListFor(Model => Model.Countries, 
               new SelectList(ViewBag.Country as System.Collections.IEnumerable"ID""Name"),               
"-- Select Country --"new { id = "ddlCountry" })
            </td>
        </tr>
        <tr>
            <td>
                City
            </td>
            <td>
                : @Html.DropDownListFor(Model => Model.States, 
                new SelectList(ViewBag.State as System.Collections.IEnumerable"ID""StateName"),
                 "-- Select State --"new { id = "ddlState", @disabled="disabled" })
            </td>
        </tr>
        <tr>
            <td>
                State
            </td>
            <td>
                : @Html.DropDownListFor(Model => Model.Cities, 
                new SelectList(ViewBag.City as System.Collections.IEnumerable"ID""CityName"),
                "-- Select City --"new { id = "ddlCity", @disabled = "disabled" })
            </td>
        </tr>
    </table>
</p>

Click Here To Download.

No comments:

Post a Comment