Monday, 26 June 2017

Cascaded Dropdown in ASP.Net MVC using Entity Framework and jQuery ajax

In this article, I am going to teach you the basic cascading Dropdown in ASP.Net MVC using Entity Framework and jQuery Ajax. So, I am going to use Visual Studio 2013 ultimate, .net framework 4.5 and MVC version 4 and below is step by step tutorial.

Creating Database Table

First of all, we need to create database table. Below is the script to create two tables that are State Master and District Master and insert some dummy data into it.

create table tblStateMaster
(
StateId int,
Name varchar(100)
)
go
insert into tblStateMaster values(1,'Maharashtra')
insert into tblStateMaster values(2,'Gujarat')
go
create table tblDistrictMaster
(
DistId int,
StateId int,
Name varchar(100)
)
insert into tblDistrictMaster values(1,1,'Mumbai')
insert into tblDistrictMaster values(2,1,'Thane')
insert into tblDistrictMaster values(3,1,'Pune')
insert into tblDistrictMaster values(4,1,'Raigad')
go
insert into tblDistrictMaster values(5,2,'Ahmedabad')
insert into tblDistrictMaster values(6,2,'Rajkot')
insert into tblDistrictMaster values(7,2,'Gandhinagar')
insert into tblDistrictMaster values(8,2,'Vadodara')
Create table

Creating ASP.Net MVC Application

Now we need to create asp.net mvc application. Open Visual Studio 2013. Go to File --> New --> Project.. as shown below.

Creating a new asp.net mvc application

Go to Installed --> Templates --> Web --> Visual Studio 2012 and select .NET Framework 4.5 and ASP.NET MVC 4 Web Application as shown below.

Selecting asp.net mvc project

In the next window, select Empty template and click on OK and new MVC project will be created as shown below

Selecting asp.net mvc templateAsp.net mvc folder architecture

Adding Entity Framework

Now the next step is Entity Framework. Go to TOOLS --> Library Package Manager --> Manage NuGet Packages for Solution.. and a new window will open. Type and search for Entity Framework and click on Install button as shown below. Once installed successfully, you can check Entity Framework in references folder.

Adding Entity Framework
Installing Entity Framework

Adding Model

Now the next step is to add model. Go to Model and add two class files i.e. Data.cs and DataContext.cs. In Data.cs file, add below lines of code to map our database table to model object.

Adding modelAdding model and context class
[Table("tblStateMaster")]
public class State
{
    [Key]
    public int StateId { get; set; }
    public string Name { get; set; }
}

[Table("tblDistrictMaster")]
public class District
{
    [Key]
    public int DistId { get; set; }
    public int StateId { get; set; }
    public string Name { get; set; }
}

In DataContext.cs file, add two properties of type DbSet which will return DbSet of State and District.

Adding context class
public class DataContext : DbContext
{
    public DbSet<State> State { get; set; }
    public DbSet<District> District { get; set; }
}

Adding Connection String

Now add the connection string as shown below. Name of connection string should be same as context class name[DataContext].

Adding web.config file
Data context and web.config file connection string

Adding Controller

Now the next step is to add controller. Go to controller folder and add a new controller file named as DropDownController. Add below lines of code.

Adding controller class
public class DropDownController : Controller
{
    DataContext dc = new DataContext();

    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetState()
    {
        var stateData = dc.State.ToList().OrderBy(x => x.Name);
        return Json(stateData, JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetDistrict(int StateId)
    {
        var districtData = dc.District.Where(x => x.StateId == StateId).OrderBy(x => x.Name);
        return Json(districtData);
    }
}

Adding jQuery File

Now the next step is to add jQuery file. You can download latest jQuery file from http://jquery.com/download/. Add jQuery file to your Scripts folder.

Adding View

Now the next step is to add View. Right click on Index ActionResult method, click Add View, give your View name as Index and do not click on strongly-typed view and click on Add. A DropDown folder will be added inside Views folder and an Index.cshtml file will be created.

Below is the code to Bind State Dropdown and District Dropdown using jQuery ajax method.

@{
    ViewBag.Title = "Index";
}

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">

    // bind State Dropdown when html is loaded
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "/DropDown/GetState",
            datatype: "Json",
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#ddlState').append('<option value="' + value.StateId + '">' + value.Name + '</option>');
                });
            }
        });
    });
    // bind State Dropdown when html is loaded

    // bind district Dropdown on selection change of State
    $(document).ready(function () {
        $('#ddlState').change(function () {
            $('#ddlDistrict').empty();
            $.ajax({
                type: "POST",
                url: "/DropDown/GetDistrict",
                datatype: "Json",
                data: { StateId: $('#ddlState').val() },
                success: function (data) {
                    $('#ddlDistrict').append('<option value>--Select--</option>');
                    $.each(data, function (index, value) {
                        $('#ddlDistrict').append('<option value="' + value.DistId + '">' + value.Name + '</option>');
                    });
                }
            });
        });
    });
    // bind district dropdownlist on Dropdown change of State
</script>

<h2>Cascading DropDownList Example</h2>
<table style="font-family:Arial;">
    <tr>
        <td>
            @Html.DropDownList("ddlState", new SelectList(string.Empty, "Value", "Text"), "--Select--", null)
        </td>
        <td>
            @Html.DropDownList("ddlDistrict", new SelectList(string.Empty, "Value", "Text"), "--Select--", null)
        </td>
    </tr>
</table>

Once View is loaded successfully, you can see expected output below.

Cascading dropdown in asp.net mvc
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON