Hi guys today I am going to demonstrate that how we can create cascade dropdown list control in asp.net MVC 5 using Razor and entity framework. Usually we need this solution.
- Create a new Project. Open Visual Studio 2013.
- Go to “File” => “New” => “Project…”.
- Select “Web” in installed templates.
- Select “ASP.NET MVC Web Application”.
- Enter the Name and choose the location.
- Click “OK”.
Create Database Tables (country and state)
Following is the database script of country and state
CREATE TABLE [dbo].[country]( [country_id] [int] IDENTITY(1,1) NOT NULL, [country_name] [varchar](50) NOT NULL, [country_abbrev] [varchar](3) NOT NULL, PRIMARY KEY CLUSTERED ( [country_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO CREATE TABLE [dbo].[state]( [state_id] [int] IDENTITY(1,1) NOT NULL, [country_id] [int] NULL, [state_name] [varchar](50) NOT NULL, [state_abbrev] [varchar](2) NOT NULL, CONSTRAINT [PK__state__81A47417FDC731AD] PRIMARY KEY CLUSTERED ( [state_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[state] WITH CHECK ADD CONSTRAINT [FK_state_country] FOREIGN KEY([country_id]) REFERENCES [dbo].[country] ([country_id]) GO
Step 3: Now open visual studio and add an edmx file (which connect your database).here I am not telling you how to create edmx file , for it you can visit my old blogs based on entity framework.
Step 4: Crate new empty Home Controller.
Step 5. Write following code in Home controller.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CascadDD.Models; namespace CascadDD.Controllers { public class HomeController : Controller { // // GET: /Home/ TeachersEntities db = new TeachersEntities(); public ActionResult Index() { ViewBag.Countries = db.countries.ToList(); ViewBag.Classes = db.states.ToList(); return View(); } private IList GetState(int Countryid) { return db.states.Where(m => m.country_id == Countryid).ToList(); } [AcceptVerbs(HttpVerbs.Get)] public JsonResult LoadStatesByCountryId(string Countryid) { var StateList = this.GetState(Convert.ToInt32(Countryid)); var StatesData = StateList.Select(m => new SelectListItem() { Text = m.state_name, Value = m.state_id.ToString(), }); return Json(StatesData, JsonRequestBehavior.AllowGet); } } } Step 5: Add New Empty Index.cshtml in Index action of Home Controller and write following code into it. @model CascadDD.Models.TeachersEntities @{ ViewBag.Title = "Index"; }
Index
Students
$(document).ready(function () {
$("#dd_Country").change(function () {
var countryId = $(this).val();
$.getJSON("../Home/LoadStatesByCountryId", { Countryid: countryId },
function (classesData) {
var select = $("#ddState");
select.empty();
select.append($('', {
value: 0,
text: "Select a State"
}));
$.each(classesData, function (index, itemData) {
select.append($('', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});
@Html.DropDownListFor(Model => Model.countries, new SelectList(ViewBag.Countries as System.Collections.IEnumerable, “country_id”, “country_name”), “Select a Country”, new { id = “dd_Country” })
@Html.DropDownListFor(Model => Model.states, new SelectList(Enumerable.Empty(), “state_id”, “statename”), “Select a State”, new { id = “ddState” })
How would you do to save selected values in the case of Create and/or Edit?
Selecting an item from the list does not give me problems, but when I want to save the selected value gives me error.
Hi, It works perfect on create, but when I try edit mode nothing happens, do you have any idea?
Dear Yogesh Sir,
I want to cascade dropdown country state and city using entity Framework 6 (code first approch).
Please help me.