In the previous article, we have discussed How to get data from database using JQuery Ajax in asp net MVC, In This article, we will discuss how to create MVC Cascading Dropdown using JQuery AJAX i.e we will cascade one dropdown list with another dropdown list in ASP.Net MVC using JQuery AJAX. In this article, we will take 3 dropdown lists, Organization, Employees, and Employee_address.
We will see how to fill the Employees dropdown list based on the data of the Organization dropdown list and then the Employee_address dropdown list based on the selected Employees.
Step 1: Create Database Table
Let’s create the database table for our task, for cascading dropdownlist in asp.net MVC using jquery ajax. I have created 3 tables called “Organization” with column Id, Name. “Employees” with [Id],[Name] ,[Salary],[OrganizationId] and Employee_address with column [Id],[Address],[City],[ZipCode],[EmployeeId].
You can find the SQL Script of the table below.
/****** Object: Table [dbo].[Employee_address] Script Date: 2/11/2022 2:51:52 PM ******/
CREATE TABLE [dbo].[Employee_address](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Address] [nvarchar](50) NULL,
[City] [nvarchar](50) NULL,
[ZipCode] [int] NULL,
[EmployeeId] [int] NULL,
CONSTRAINT [PK_Departments] PRIMARY KEY CLUSTERED
(
[Id] ASC
))
/****** Object: Table [dbo].[Employees] Script Date: 2/11/2022 2:51:52 PM ******/
CREATE TABLE [dbo].[Employees](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Salary] [float] NULL,
[OrganizationId] [int] NULL,
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[Id] ASC
) ON [PRIMARY])
/****** Object: Table [dbo].[Organization] Script Date: 2/11/2022 2:51:52 PM ******/
CREATE TABLE [dbo].[Organization](
[Id] [int] IDENTITY(1,1) NOT NULL,
[CompanyName] [nvarchar](50) NULL,
CONSTRAINT [PK_Organization] PRIMARY KEY CLUSTERED
(
[Id] ASC
))
GO
SET IDENTITY_INSERT [dbo].[Employee_address] ON
GO
INSERT [dbo].[Employee_address] ([Id], [Address], [City], [ZipCode], [EmployeeId]) VALUES (1, '3899 Grey Fox Farm Road', 'Houston', 20120, 1)
GO
INSERT [dbo].[Employee_address] ([Id], [Address], [City], [ZipCode], [EmployeeId]) VALUES (2, '4790 Happy Hollow Road', 'Wilmington', 28405, 2)
GO
INSERT [dbo].[Employee_address] ([Id], [Address], [City], [ZipCode], [EmployeeId]) VALUES (3, '742 Arbutus Drive', 'Miami', 33145, 3)
GO
INSERT [dbo].[Employee_address] ([Id], [Address], [City], [ZipCode], [EmployeeId]) VALUES (4, '1852 Willow Greene Drive', 'Montgomery', 5522, 4)
GO
INSERT [dbo].[Employee_address] ([Id], [Address], [City], [ZipCode], [EmployeeId]) VALUES (5, '7742 Arbutus Drive', 'Miami', 33145, 5)
GO
INSERT [dbo].[Employee_address] ([Id], [Address], [City], [ZipCode], [EmployeeId]) VALUES (6, '742 Drive', 'Miami', 33145, 6)
GO
SET IDENTITY_INSERT [dbo].[Employee_address] OFF
GO
SET IDENTITY_INSERT [dbo].[Employees] ON
GO
INSERT [dbo].[Employees] ([Id], [Name], [Salary], [OrganizationId]) VALUES (1, 'Mark', 6000, 1)
GO
INSERT [dbo].[Employees] ([Id], [Name], [Salary], [OrganizationId]) VALUES (2, 'Henry', 3000, 1)
GO
INSERT [dbo].[Employees] ([Id], [Name], [Salary], [OrganizationId]) VALUES (3, 'Thomas', 4000, 2)
GO
INSERT [dbo].[Employees] ([Id], [Name], [Salary], [OrganizationId]) VALUES (4, 'Jack', 6000, 2)
GO
INSERT [dbo].[Employees] ([Id], [Name], [Salary], [OrganizationId]) VALUES (5, 'Tim', 5000, 3)
GO
INSERT [dbo].[Employees] ([Id], [Name], [Salary], [OrganizationId]) VALUES (6, 'Luis', 4000, 3)
GO
INSERT [dbo].[Employees] ([Id], [Name], [Salary], [OrganizationId]) VALUES (7, 'Southy', 6000, 3)
GO
SET IDENTITY_INSERT [dbo].[Employees] OFF
GO
SET IDENTITY_INSERT [dbo].[Organization] ON
GO
INSERT [dbo].[Organization] ([Id], [CompanyName]) VALUES (1, 'Microsoft')
GO
INSERT [dbo].[Organization] ([Id], [CompanyName]) VALUES (2, 'Google')
GO
INSERT [dbo].[Organization] ([Id], [CompanyName]) VALUES (3, 'Apple')
GO
SET IDENTITY_INSERT [dbo].[Organization] OFF
GO
ALTER TABLE [dbo].[Employee_address] WITH CHECK ADD CONSTRAINT [FK_Departments_Employees] FOREIGN KEY([EmployeeId])
REFERENCES [dbo].[Employees] ([Id])
GO
ALTER TABLE [dbo].[Employee_address] CHECK CONSTRAINT [FK_Departments_Employees]
GO
ALTER TABLE [dbo].[Employees] WITH CHECK ADD CONSTRAINT [FK_Employees_Organization] FOREIGN KEY([OrganizationId])
REFERENCES [dbo].[Organization] ([Id])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Organization]
GO
Step 2 :Open your VS19 or VS22, create an empty MVC website if don’t know how to create an empty project then please read below basic crud operation article.
Step 3 : we are using Entity Framework for Cascading dropdown
In Model Folder, right-click then select Add New Item -> Data option on the left side menu. select ADO .net entity framework.
and follow the below step.
Step 4: Adding HomeController in our project
Now let’s add a Homecontroller in our project for showing the list, Right-click on the Controller folder in the project =>add an empty controller.
Now open Homecontroller.cs and let’s write the code in our controller, and add the following action methods. Here, I am going to add one action method to our controller which returns all Index view.
Homecontroller.cs
using Cascading.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Cascading.Controllers
{
public class HomeController : Controller
{
DemoDatabaseEntities context = new DemoDatabaseEntities();
// GET: Home
public ActionResult Index()
{
var Organizations = context.Organizations.ToList();
return View(Organizations);
}
//retrun all employee by OrganizationsId
[HttpPost]
public JsonResult GetEmployeedByOrganizationIdId(int OrganizationId)
{
var Employees = (from r in context.Employees
where r.OrganizationId == OrganizationId
select new
{
r.Id,
r.Name
}).ToList();
return Json(Employees, JsonRequestBehavior.AllowGet);
}
//return all employee address because a employee can have multiple address
[HttpPost]
public JsonResult GetEmployeeAddressBydId(int EmployeeId)
{
var EmployeesAddress = (from r in context.Employee_address
where r.EmployeeId == EmployeeId
select new
{
r.Id,
r.Address
}).ToList();
return Json(EmployeesAddress, JsonRequestBehavior.AllowGet);
}
}
}
Step 5: Create copy paste the below code in Index.cshtml view
@model IEnumerable<Cascading.Models.Organization>
@{
ViewBag.Title = "Index";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<h2>Cascading Dropdownlist Example</h2>
<div>
<label>Organizations</label>
<select id="ddlOrganization" onchange="LoadEmployees()">
<option>Select Organization</option>
@if (Model != null && Model.Count() > 0)
{
foreach (var item in Model)
{
<option value="@item.Id">@item.CompanyName</option>
}
}
</select>
<br />
<br />
<label>Employees</label>
<select id="ddlEmployees" onchange="LoadEmployeesAddress()">
</select>
<br />
<br />
<label>Employees Address</label>
<select id="ddlAddress">
</select>
</div>
<script type="text/javascript">
function LoadEmployees()
{
var OrzanId = $("#ddlOrganization").val();
if (OrzanId) {
$.ajax({
type: "POST",
url: "/Home/GetEmployeedByOrganizationIdId",
data: { OrganizationId: OrzanId},
success: function (empdata) {
var ddlEmployees = $("#ddlEmployees");
ddlEmployees.empty()
$("#ddlAddress").empty();
if (empdata) {
ddlEmployees.append($('<option/>', {
value: 0,
text: "Select a employees"
}));
$.each(empdata, function (index, empData) {
ddlEmployees.append($('<option/>', {
value: empData.Id,
text: empData.Name
}));
});
}
}
,
error: function (ex) {
alert(ex);
}
});
}
}
function LoadEmployeesAddress() {
var EmployeesId = $("#ddlEmployees").val();
if (EmployeesId) {
$.ajax({
type: "POST",
url: "/Home/GetEmployeeAddressBydId",
data: { EmployeeId: EmployeesId },
success: function (empaddressdata) {
var ddlAddress = $("#ddlAddress");
ddlAddress.empty()
if (empaddressdata) {
$.each(empaddressdata, function (index, empaddData) {
ddlAddress.append($('<option/>', {
value: empaddData.Id,
text: empaddData.Address
}));
});
}
}
,
error: function (ex) {
alert(ex);
}
});
}
}
</script>
Step:6 Build Run Project
The post [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- Upload file with .net core MVC using ajax and pass as model
- How to change the Assemby and the Object type on the Newtonsoft.Json serialization/deserialization? Am using .NET MVC 3 and WPF
- Update WebGrid and DropDown through Ajax in MVC 4
- dropdown menu populate another c# mvc json ajax
- how to get the selected item from html dropdown list and pass it to another controller in mvc c#
- dropdown selection in HTML table cell, using selenium webdriver and C#
- Why is this value zero after ajax call finishes (asp.net mvc 3 and jQuery)?
- MVC 4: Calling action method on dropdown list select change
- How to bind a DataTable to a DropDownList using MVC RAZOR?
- How can I change the username and password of an application pool using the .NET ApplicationPool class?
- .NET Core 3 MVC download a file from HTTP and re-deliver to client using minimum memory
- how to parse json data from a rest api using C# in the ASP.Net Core MVC model and display it on a HTML page
- Send object to mvc controller using ajax
- Cannot post to another domain using ajax despite having CORS enabled
- How can I access another user's resources (specifically emails) using Microsoft Graph in an MVC app?
- How can I bind to the count of the items source in XAML using a style and a DataTrigger?
- MVC 5 add dynamic fields to form using jquery and save it to model
- bind Day (1-31) to dropdown programmatically and 0's to day < 10?
- How to update documents using another field's value using MongoDB and C#?
- How can I structure an ASP.NET MVC application with a "Core" database and individual derived databases using Entity Framework?
- Post Knockout.js viewmodel to ASP.NET MVC Controller action using ajax results in null-values
- ASP.NET MVC 5.1 EditorFor and DisplayFor not Using Custom Templates
- How to get usernames and userIDs from asp.net-membership and bind it to dropdown listz?
- Is it possible to using Type Inference for the first parameter and specify another type
- Can't Set and Get cookie using C# under ASP.NET MVC
- I want to save an ID from a table to another table using asp.net mvc 5
- defining MySqlConnection in one class and using it in another class to work with DB
- How can i fill a C# listview by using foreach loop a column and another foreach for second column so that 2nd loop do not over write first
- Using Razor and Spark simultaineously in ASP.NET MVC 2 project
- C#, winform - List box selection using up and down arrow key?
- Designing a "busy" dialog using InteractionRequests
- Image to byte[], Convert and ConvertBack
- API to Object (with array) in C#
- Create combinations of german words for spellchecking
- MVVM pattern, ViewModel Collection
- How to fire TextChanged event on a Xamarin Forms entry field programmatically?
- C# Rename Directory, Copy All Contents If Directory Already Exists
- How to put message into dead-letter and process it after some interval in azure function
- Using WebClient to pass arrays as part of message body for post action
- Problem with multithreading concurrency in file download in web service
- Vector2.MoveTowards not moving my object in a coroutine
- Recieved emails not read in the program during the reconnection session using EWS Streaming Notification
- How to get user information after successful authentication?
- How to throttle events RX?
- Control flickers while drawing in .Net Compact Framework
- iTextSharp - Unable to draw rectangle over tablecell background color
- Server.MapPath returning incorrect path
- Difference between NetworkToHostOrder and HostToNetworkOrder?
- Test with Moq if a method of external library is called
- xpath for foreach loop