Introduction
In this article we will learn how to bind data from a table to a DropDownList in MVC using LINQ to SQL and learn how to populate a child dropdown list depending on each new value as values are selected in the parent's DropDownList.
Database structure
Create two tables in the database with the names Country and State.
The following is the create table code for the country table:
- CREATE TABLE [dbo].[country]
- (
- [countryid] [int] NOT NULL,
- [countryname] [nvarchar](50) NULL,
- )
In the preceding SQL query, countryid is the primary key.
The following is the create table code for the state table:
- CREATE TABLE [dbo].[state]
- (
- [stateid] [int] NOT NULL,
- [statename] [nvarchar](50) NULL,
- [countryid] [int] NULL,
- )
In the preceding SQL query, stateid is the primary key and countryid is the foreign key reference by country table.
Adding a LINQ to SQL Class
Step 1
Right-click on the project and select "Add new item", then select Data from the templates.
Step 2
Choose "LINQ to SQL classes" from the list and provide a name. Now after clicking on Add, you can see the .dbml file in the project.
Step 3
Drag the country and state tables from the database in the Server Explorer.
Create a dft Controller
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Data.SqlClient;
- namespace dropdownlist.Controllers
- {
- public class dftController : Controller
- {
- DataClasses1DataContext db = new DataClasses1DataContext();
- //
- // GET: /dft/
- public ActionResult Index()
- {
- DataClasses1DataContext db = new DataClasses1DataContext();
- ViewBag.countryid = new SelectList(db.countries, "countryid", "countryname");
- ViewBag.states = new SelectList(new List<state>() ,"stateid","statename");
- return View();
- }
- public IList<state> Getstate(int id)
- {
- return db.states.Where(m => m.countryid == id).ToList();
- }
- public JsonResult GetJsonState(int id)
- {
- var stateListt = this.Getstate(Convert.ToInt32(id));
- var statesList = stateListt.Select(m => new SelectListItem()
- {
- Text = m.statename,
- Value = m.countryid.ToString()
- });
- return Json(statesList, JsonRequestBehavior.AllowGet);
- }
- }
- }
Create a view for showing the values in the DropDownList
Right-click on the Index ActionResult method and select Add View. After selecting Add View, a dialog box will open. The view name is the index by default. Now select your model class and click on the OK button.
- @model dropdownlist.country
- @{
- ViewBag.Title = "Index";
- }
- <h2>Index</h2>
- @using (Html.BeginForm())
- {
- @Html.DropDownList("country", ViewBag.countryid as SelectList, "Select a Country", htmlAttributes: new { onchange = "Getstate()" })
- @Html.DropDownList("State", ViewBag.states as SelectList, "Choose State", new { @class = "inputBox", @id = "DropDownListStates" })
- }
- <script>
- function GetState() {
- $.ajax({
- url: "@Url.Action("GetJsonState", "dft")",
- dataType: "json",
- type: "GET",
- data:{id:$("#country").val()},
- error: function () {
- },
- beforeSend: function () {
- },
- success: function (data) {
- var items = "";
- items = "<option value=''>Choose State</option>";
- $.each(data, function (i, item) {
- items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
- });
- $("#DropDownListStates").html(items);
- }
- });
- }
- </script>


Summary
In this article we learned how to bind data from a table to a DropDownList in MVC using LINQ to SQL and learn how to populate a child dropdown list depending on each new value as values are selected in the parent's DropDownList.

Faridul IslamPosted Feb 24, 2020, 8:29 PM
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'City'. [error]
Ambareesh cPosted Nov 26, 2018, 12:24 AM
@Html.DropDownList("country", ViewBag.countryid as SelectList, "Select a Country", htmlAttributes: new { onchange = "Getstate()" }). In this line getting error like Uncaught ReferenceError: Getstate is not defined at HTMLSelectElement.onchange so can you help me out...
Honey ModiPosted Aug 22, 2017, 1:28 AM
Http://localhost:2212/Home/@Url.Action('GetJsonState','Home')?id=1 404 (Not Found)... heya. i m getting this and my state list not getting populated
Nathalie DesrosiersPosted Feb 14, 2017, 7:15 AM
In your function, "dft" stands for what?
Atul RawatPosted Oct 5, 2015, 12:04 AM
check this line @Html.DropDownList("country", ViewBag.countryid as SelectList, "Select a Country", htmlAttributes: new { onchange = "Getstate()" })
John qeqwPosted Oct 4, 2015, 11:20 AM
Im getting error in chrome console "Getstate is not defined"
Francesco SerafiniPosted Jul 16, 2015, 6:46 AM
??????? ??????? ?? ???? ??????, ?????? ?????????.???????, ?? ????? ? ???? ??, ??? ???????: ..... error: function () { var items = ""; items = "<option value=''>Choose Country</option>"; $("#DropDownListStates").html(items); }, ..... ??? - ???????
Atul RawatPosted Jul 16, 2015, 12:14 AM
Please read again json code....
Francesco SerafiniPosted Jul 15, 2015, 11:02 AM
Just a silly question: how to reset the "State" dropdownlist to its initial value (i.e.: "Choose State") as the "Country" dropdownlist is set back to its initial value (i.e.: "Select a Country"). Thx
Vipin TyagiPosted Jun 4, 2015, 2:56 AM
Great One Rawat.....
Abhishek JaiswalPosted Jun 3, 2015, 4:14 PM
Nice Read!! :)
Santhakumar MunuswamyPosted Jun 3, 2015, 2:45 PM
Thanks for nice article
Akash NaginaPosted Jun 3, 2015, 1:38 PM
Very Helpful!!
Gowtham KPosted Jun 3, 2015, 1:00 PM
Good one
Shridhar SharmaPosted Jun 3, 2015, 12:13 PM
nice article buddy.
NitinPosted Jun 3, 2015, 9:21 AM
nice