Tuesday, July 30, 2013

How to Use Country/State/City in MVC3 Cascading DropdownList Using Jquery with Example

 
In this article i will show you how you can create a cascading dropdown list using jquery
in mvc3 application.In this i have used asp.net mvc and jquery.

Here is the article in which i have shown how you can retrieve value of cascaded drop down list in mvc3 in controller
So for this first you needed to create a new mvc3 application. add a controller and a model class file. Now in your model file add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Cascadded_ddl.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}


Here i have created a class for state and city. in country model class i have added all the other classes. Here public SelectList FilteredCity { get; set; } i have used for passing the value after storing in it when user make an Ajax request.

Now come to your controller and add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cascadded_ddl.Models;
namespace Cascadded_ddl.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }
        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStaeId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }
    }
}

In above code i have made the collection for city and state. The below code is used for making the ajax call.
//Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStaeId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }

Now create a view for index action result, and add the below code.
@model Cascadded_ddl.Models.CountryModel
@{
    ViewBag.Title = "Index";
}
<script language="javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value=`0`> Please wait...</option>";
        $(`#ddlcity`).html(procemessage).show();
        var url = "/Home/GetCityByStaeId/";
    
        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value=`0`>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $(`#ddlcity`).html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
    MVC3 Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm("", ""))
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">
    </select>

}

Here is the jquery code which i have used for making ajax call in change event of the state ddl.
<script language="javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value=`0`> Please wait...</option>";
        $(`#ddlcity`).html(procemessage).show();
        var url = "/Home/GetCityByStaeId/";
    
        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value=`0`>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $(`#ddlcity`).html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>


Here i have used the   var url = "/Home/GetCityByStaeId/"; in this Home is the controller name and GetCityByStaeId is the actionresult method in controller.

The below mention piece of code is responsible for showing the please wait message until the response from server not get finish
  var procemessage = "<option value=`0`> Please wait...</option>";
        $(`#ddlcity`).html(procemessage).show();


Now run the application.
MVC3 Cascading Dropdown List

Now select the state

MVC3 Cascading Dropdown List

Her please wait message will come until the processing not get completed .

Here our controller is called. and in parameter we are getting the state id.
MVC3 Cascading Dropdown List

now output

MVC3 Cascading Dropdown List

No comments:

Post a Comment