24 July 2016 Sudhanshu Ranjan 1.32k

Bind dropdown in MVC using jquery with C#

In my today article, I am going to explain how to bind the multiple dropdown (Like: Country, State, City) in MVC using JQuery, ajax, C#. It is very common in your development life and you will get these types situation to bind dropdown which depends on others dropdown. You can understand that you have to populate data like Country, State and City on webpage.

Follow the step that you can implement.


Step 1: Should Install Visual Studio, SQL Server, MVC4 and above.
Step 2:  Create Database and add Country, State, City table.

USE [TestDatabase]--Database Name
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Country](
	[CountryId] [int] IDENTITY(1,1) NOT NULL,
	[CountryName] [varchar](50) NULL,
 CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED 
(
	[CountryId] 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
SET IDENTITY_INSERT [dbo].[Country] ON
INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (1, N'India')
INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (2, N'USA')
INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (3, N'Japan')
INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (4, N'Nepal')
INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (5, N'SriLanka')
SET IDENTITY_INSERT [dbo].[Country] OFF

/****** Object:  Table [dbo].[State]    Script Date: 07/24/2016 15:58:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[State](
	[StateId] [int] IDENTITY(1,1) NOT NULL,
	[CountryId] [int] NULL,
	[StateName] [varchar](50) NULL,
 CONSTRAINT [PK_State] PRIMARY KEY CLUSTERED 
(
	[StateId] 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
SET IDENTITY_INSERT [dbo].[State] ON
INSERT [dbo].[State] ([StateId], [CountryId], [StateName]) VALUES (1, 1, N'Bihar')
INSERT [dbo].[State] ([StateId], [CountryId], [StateName]) VALUES (2, 1, N'Uttar Pradesh')
INSERT [dbo].[State] ([StateId], [CountryId], [StateName]) VALUES (3, 1, N'Goa')
INSERT [dbo].[State] ([StateId], [CountryId], [StateName]) VALUES (4, 2, N'New Yark')
INSERT [dbo].[State] ([StateId], [CountryId], [StateName]) VALUES (5, 2, N' 	Texas')
SET IDENTITY_INSERT [dbo].[State] OFF


/****** Object:  Table [dbo].[City]    Script Date: 07/24/2016 15:58:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[City](
	[CityId] [int] IDENTITY(1,1) NOT NULL,
	[CountryId] [int] NULL,
	[StateId] [int] NULL,
	[CityName] [varchar](50) NULL,
 CONSTRAINT [PK_City] PRIMARY KEY CLUSTERED 
(
	[CityId] 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
SET IDENTITY_INSERT [dbo].[City] ON
INSERT [dbo].[City] ([CityId], [CountryId], [StateId], [CityName]) VALUES (1, 1, 1, N'Gaya')
INSERT [dbo].[City] ([CityId], [CountryId], [StateId], [CityName]) VALUES (2, 1, 1, N'Patna')
INSERT [dbo].[City] ([CityId], [CountryId], [StateId], [CityName]) VALUES (3, 1, 1, N'AurangaBad')
INSERT [dbo].[City] ([CityId], [CountryId], [StateId], [CityName]) VALUES (4, 2, 5, N'San Antonio')
INSERT [dbo].[City] ([CityId], [CountryId], [StateId], [CityName]) VALUES (5, 2, 5, N'Texas City')
SET IDENTITY_INSERT [dbo].[City] OFF
/****** Object:  ForeignKey [FK_City_Country]    Script Date: 07/24/2016 15:58:56 ******/
ALTER TABLE [dbo].[City]  WITH CHECK ADD  CONSTRAINT [FK_City_Country] FOREIGN KEY([CountryId])
REFERENCES [dbo].[Country] ([CountryId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[City] CHECK CONSTRAINT [FK_City_Country]
GO
/****** Object:  ForeignKey [FK_City_State]    Script Date: 07/24/2016 15:58:56 ******/
ALTER TABLE [dbo].[City]  WITH CHECK ADD  CONSTRAINT [FK_City_State] FOREIGN KEY([StateId])
REFERENCES [dbo].[State] ([StateId])
GO
ALTER TABLE [dbo].[City] CHECK CONSTRAINT [FK_City_State]
GO
/****** Object:  ForeignKey [FK_State_Country]    Script Date: 07/24/2016 15:58:56 ******/
ALTER TABLE [dbo].[State]  WITH CHECK ADD  CONSTRAINT [FK_State_Country] FOREIGN KEY([CountryId])
REFERENCES [dbo].[Country] ([CountryId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[State] CHECK CONSTRAINT [FK_State_Country]
GO

Step 3: Create new MVC application

Step 4:  Add database using ADO.NET Entity Data Model Wizard.

Step 5:  In HomeController, create Action for bind the dropped down.

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


namespace CountryStateDroppedDown.Controllers
{
    public class HomeController : Controller
    {
        DatabaseEntities db = new DatabaseEntities();

        public ActionResult Index()
        {
            ViewBag.CountryList = new SelectList(db.Countries, "CountryId", "CountryName");

            return View();
        }

        public JsonResult BindState(int CountryId)
        {
            var stateList = from x in db.States where x.CountryId == CountryId select x;

            return Json(new SelectList(stateList, "StateId", "StateName"), JsonRequestBehavior.AllowGet);
        }


        public JsonResult BindCity(int CountryId, int StateId)
        {
            var citylist = from x in db.Cities where x.CountryId == CountryId && x.StateId == StateId select x;

            return Json(new SelectList(citylist, "CityId", "CityName"), JsonRequestBehavior.AllowGet);
        }
    }
}

Step 6:  In Index View, add following HTML code.

@model CountryStateDroppedDown.Country
@{
    ViewBag.Title = "Home Page";
}

@Scripts.Render("~/bundles/jquery")


@using (Html.BeginForm())
{   

    <div>
        @Html.Label("Country")
        @Html.DropDownListFor(x => x.CountryId, ViewBag.CountryList as SelectList, "--Select a Country--")
    </div>

    <div>
        @Html.Label("State")
        <select id="ddlState" name="ddlState"></select>
    </div>

    <div>
        @Html.Label("City")
        <select id="ddlCity" name="ddlCity"></select>
    </div>
}

Step 7: In Index View, Add following JQuery code. In this code we are calling action method at change of dropped down value.


<script type="text/javascript">
    $(document).ready(new function () {
        $("#CountryId").change(function () {
            var countryid = $('#CountryId').val();

            $('#ddlState').html('');
            $('#ddlCity').html('');


            $.ajax({
                type: "GET",
                url: '@Url.Action("BindState", "Home")',
                data: { "CountryId": countryid },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successFunc
            });

            function successFunc(data, status) {
                var items = '<option>--Select a State--</option>';
                $.each(data, function (i, state) {
                    items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                });
                $('#ddlState').html(items);

            }


            $("#ddlState").change(function () {
                var countryid = $('#CountryId').val();
                var stateid = $('#ddlState').val();

                $.ajax({
                    type: "GET",
                    url: '@Url.Action("BindCity", "Home")',
                    data: { "CountryId": countryid, "StateId": stateid },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: successFunc
                });

                function successFunc(data, status) {
                    var items = '<option>--Select a City--</option>';
                    $.each(data, function (i, city) {
                        items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
                    });
                    $('#ddlCity').html(items);

                }
            });
        });
    });
</script>

Step 8:  make sure JQuery Library should be added on the page.

@Scripts.Render("~/bundles/jquery")

 

Finally, You will get the output.

 

You can share at :

About Author
Sudhanshu Kumar Ranjan | Lead Engineer at HCL Technologies | Expertise in Microsoft Technology | Author | Blogger | Programmer
Know More
Connect with him on Facebook | Google+ | LinkedIn | Twitter

Recommended Post

Leave a comment

About Dotnet Cube

It's my blog - Dotnet Cube, where you will learn and get solutions about programming, web designing and development. I started this website to share my knowledge and experience which might help someone.

You can get more details about me and my blog at About Us page.

Subscribe Newsletter

Subscribe to our monthly newsletter to get the latest industry news, Media Group updates and our current specials.

Follow On Us...

Home | About | Advertise | Copyrights | Privacy | Contact | Admin

Copyrights © 2015-2017 dotnetcube.com. All rights reserved