Hello everyone, Here we will see an example of Cascading Dropdownlist in ASP.NET MVC. This is a commonly used scenario used in any web application where the one list depends on the selection of another list.

Cascading Drodpwnlist in ASPP.NET MVC:


Here we will create a simple example of Cascading Dropdownlist in ASP.NET MVC using ajax jquery.

Create DataBase and Tables:

CREATE DATABASE Debugonweb

USE [Debugonweb]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[City](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[StateID] [bigint] NULL,
[City] [varchar](100) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[State](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[State] [varchar](50) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO

Create Stored Procedure:

USE [Debugonweb]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[uspGetCityByState]
@pStateID BIGINT
AS
BEGIN
SET NOCOUNT ON;
SELECT ID,City FROM [dbo].[City] WHERE [email protected]
SET NOCOUNT OFF;
END
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[uspGetState]
AS
BEGIN
SET NOCOUNT ON;
SELECT ID,State FROM [dbo].[State]
SET NOCOUNT OFF;
END
GO

Insert Dummy Data:

USE [Debugonweb]
GO
SET IDENTITY_INSERT [dbo].[City] ON

GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (1, 1, N'Lucknow')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (2, 1, N'Varanasi')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (3, 1, N'Jhansi')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (4, 1, N'Muradabad')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (5, 2, N'Gwalior')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (6, 2, N'Indore')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (7, 2, N'Bhopal')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (8, 2, N'Jabalpur')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (9, 3, N'Jalandhar')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (10, 3, N'Amritsar')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (11, 3, N'Chandigarh')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (12, 3, N'Ludhiana')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (13, 4, N'Jaipur')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (14, 4, N'Jodhpur')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (15, 4, N'Ajmer')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (16, 4, N'Kota')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (17, 4, N'Udaipur')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (18, 5, N'Surat')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (19, 5, N'Ahmedabad')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (20, 5, N'Rajkot')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (21, 5, N'Gandhinagar')
GO
INSERT [dbo].[City] ([ID], [StateID], [City]) VALUES (22, 5, N'Vadodara')
GO
SET IDENTITY_INSERT [dbo].[City] OFF
GO
SET IDENTITY_INSERT [dbo].[State] ON

GO
INSERT [dbo].[State] ([ID], [State]) VALUES (1, N'Uttar Pradesh')
GO
INSERT [dbo].[State] ([ID], [State]) VALUES (2, N'Madhya Pradesh')
GO
INSERT [dbo].[State] ([ID], [State]) VALUES (3, N'Punjab')
GO
INSERT [dbo].[State] ([ID], [State]) VALUES (4, N'Rajasthan')
GO
INSERT [dbo].[State] ([ID], [State]) VALUES (5, N'Gujrat')
GO
SET IDENTITY_INSERT [dbo].[State] OFF
GO

Create ASP.NET MVC Application:

Setup Model:

Step 1- Open Visual Studio and Create an ASP.NET MVC application called CascadingDropdownList.

Step 2- Choose an empty application and proceed.

Step 3- Right Click on the Model Folder and create a class called StateModel and replace the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CascadingDropdownList.Models
{
public class StateModel
{
public Int64 ID { get; set; }
public string State { get; set; }
}
}

Step 4-  Right Click on the Model folder and create a class called CityModel. Replace the following code in the class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CascadingDropdownList.Models
{
public class CityModel
{
public Int64 ID { get; set; }
public Int64 StateID { get; set; }
public string City { get; set; }

}
}

Step 5- Right click on the Model folder and Create an Interface called IStateCityRepository. Replace the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CascadingDropdownList.Models
{
interface IStateCityRepository
{
List<StateModel> GetStateList();
List<CityModel> GetCityList(string iStateID);
}
}

Step 6- Right click on the Model folder and create a class called StateCityRepository. This class implements  IStateCityRepository interface.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace CascadingDropdownList.Models
{
public class StateCityRepository:IStateCityRepository
{
public List<StateModel> GetStateList()
{
List<StateModel> lstState = new List<StateModel>();
try
{
StateModel objStateModel = null;
using (SqlConnection dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ToString()))
{
using (SqlCommand cmdGetStateList = new SqlCommand("[dbo].[uspGetState]", dbCon))
{
cmdGetStateList.CommandType = CommandType.StoredProcedure;


if (dbCon.State == ConnectionState.Closed)
dbCon.Open();
using (SqlDataReader drGetStateList = cmdGetStateList.ExecuteReader())
{
if (drGetStateList.HasRows)
{
while (drGetStateList.Read())
{
objStateModel = new StateModel();
objStateModel.ID = drGetStateList.GetInt64(0);
objStateModel.State = drGetStateList.GetString(1);
lstState.Add(objStateModel);
}
}
}

}
}
}
catch (Exception ex)
{ }
return lstState;
}


public List<CityModel> GetCityList(string iStateID)
{
List<CityModel> lstCity = new List<CityModel>();
try
{
CityModel objCityModel = null;
using (SqlConnection dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ToString()))
{
using (SqlCommand cmdGetCityList = new SqlCommand("[dbo].[uspGetCityByState]", dbCon))
{
cmdGetCityList.CommandType = CommandType.StoredProcedure;
cmdGetCityList.Parameters.AddWithValue("@pStateID", iStateID);

if (dbCon.State == ConnectionState.Closed)
dbCon.Open();
using (SqlDataReader drGetCityList = cmdGetCityList.ExecuteReader())
{
if (drGetCityList.HasRows)
{
while (drGetCityList.Read())
{
objCityModel = new CityModel();
objCityModel.ID = drGetCityList.GetInt64(0);
objCityModel.City = drGetCityList.GetString(1);
lstCity.Add(objCityModel);
}
}
}

}
}
}
catch (Exception ex)
{ }
return lstCity;
}
}
}

Create Controller:

Right Click on the Controller folder and Create a Controller called HomeController. Replace the following code in the HomeController.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CascadingDropdownList.Models;
namespace CascadingDropdownList.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/

public ActionResult Index()
{
return View();
}
public JsonResult GetState()
{
IStateCityRepository objStateCityRepository = new StateCityRepository();
List<StateModel> lstStateModel = objStateCityRepository.GetStateList();
return Json(lstStateModel, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCity(string iStateID)
{
IStateCityRepository objStateCityRepository = new StateCityRepository();
List<CityModel> lstCityModel = objStateCityRepository.GetCityList(iStateID);
return Json(lstCityModel, JsonRequestBehavior.AllowGet);
}
}
}

Create View:

Right Click on the Index Action method in HomeController and Create a View called Index.

@{
ViewBag.Title = "Index";
}


<html>
<head>
<title>
Cascading Dropdownlist
</title>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "/Home/GetState",
dataType: "json",
type: "Get",
data: {},
success: function (data) {
$("#ddlState").empty();
$("#ddlState").append("<option value='0'>State</option>");
$.each(data, function (i, val) {
$("#ddlState").append("<option value=\"" + val.ID + "\">" + val.State + "</option>");
});
}
});
});
function GetCityByState()
{
$.ajax({
url: "/Home/GetCity",
type: "Get",
dataType: "json",
data: { iStateID: $("#ddlState").val() },
success: function (data) {
$("#ddlCity").empty();
$("#ddlCity").append("<option value='0'>City</option>");
$.each(data, function (i, val) {
$("#ddlCity").append("<option value=\"" + val.ID + "\">" + val.City + "</option>");
});
}
})
}


</script>
</head>
<body>
<div>
<label>
State
</label>
<select id="ddlState" onchange="GetCityByState();">
<option value="0">State</option>
</select>

</div>
<br />
<div>
<label>City</label>
<select id="ddlCity">
<option value="0">City</option>
</select>
</div>
</body>
</html>

Add Connection String in Web.Config:

Add the following connection string inside the configuration tag of Systm.web.

<connectionStrings>
<add name="dbConnection" connectionString="Data Source=Your-DataSource; Initial Catalog=Debugonweb; Integrated Security=true" providerName="System.Data.SqlClient" />
</connectionStrings>

Change your connection string according to your sql server configuration.

Output:

Cascading Dropdownlist

View More:

Conclusion:

I hope this is a useful topic for you if you just started working on ASP.NET MVC. Please don’t hesitate to comment for any technical help. Your feedback and suggestions are always welcome to me.

Thank You.

Leave a Comment