Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Wednesday, December 9, 2015

Cascading DropDownList In MVC

In this article I am going to explain how to create cascading dropdownlist in MVC.

Step1

In Visual Studio Go to  Menu File->New->Project, and click on Project.



Step2


After Clicking on project the given below window will be open (the output looks like):


select ASP.NET MVC 4 Web Appliaction rename the name value to (CascadingDropDownMVC), then click on OK button

Step3

After completing the step 2 new window will be open the output is looks like


In it select the Basic  project template and click on "OK" button, after clicking on "OK" button your solution explorer look like



Step 4

After the completing step 3 , I add a class in my model (Right click on Model folder at solution explorer) the output will look like(Here click on class menu item)



Now new window will be open,  rename the class name (StateCity.cs)  (output look like) then click on Add Button.


your "StateCity.cs" class has been created.

Step 5

Before writing the code in class firstly create  two tables "city" and "state" in your database ,
you may use the given below script for tables creation.

DataBase Structure of City,State


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,
                [StateName] [varchar](50) NOT NULL,
                [active] [bit] NULL,
                [Latitude] [varchar](35) NULL,
                [Longitude] [varchar](35) NULL,
 CONSTRAINT [PK_StateMaster] 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], [StateName], [active], [Latitude], [Longitude]) VALUES (3, N'Andaman and Nicobar', 1, N'6deg.  and 14deg.N', N'92deg. and 94deg. E')
INSERT [dbo].[State] ([StateID], [StateName], [active], [Latitude], [Longitude]) VALUES (4, N'Andhra Pradesh', 1, N'12deg.41min and 22Deg. N', N'77deg.and 84deg.40min E')
INSERT [dbo].[State] ([StateID], [StateName], [active], [Latitude], [Longitude]) VALUES (5, N'Assam', 1, N'24deg.  3min and 27deg. 58min N', N'89deg.5min and 96deg. 1min E')
SET IDENTITY_INSERT [dbo].[State] OFF
/****** Object:  Table [dbo].[TCity]    Script Date: 12/10/2015 12:34:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TCity](
                [CityID] [int] IDENTITY(1,1) NOT NULL,
                [CityName] [varchar](100) NOT NULL,
                [StateId] [int] NOT NULL,
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].[TCity] ON
INSERT [dbo].[TCity] ([CityID], [CityName], [StateId]) VALUES (2, N'ANDAMAN ISLAND', 3)
INSERT [dbo].[TCity] ([CityID], [CityName], [StateId]) VALUES (3, N'NICOBAR ISLAND', 3)
SET IDENTITY_INSERT [dbo].[TCity] OFF
/****** Object:  ForeignKey [fk_StateId]    Script Date: 12/10/2015 12:34:50 ******/
ALTER TABLE [dbo].[TCity]  WITH CHECK ADD  CONSTRAINT [fk_StateId] FOREIGN KEY([StateId])
REFERENCES [dbo].[State] ([StateID])
GO
ALTER TABLE [dbo].[TCity] CHECK CONSTRAINT [fk_StateId]


Now we write the code of  "StateCity.cs" class.

StateCity.cs


using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace CascadingDropDownMVC.Models
{
    public class StateCity
    {

      //return connection string

        string Constr = ConfigurationManager.ConnectionStrings["Con"].ToString();
     
        public List<SelectListItem> State = null;
        public int StateID { set; get; }
        public List<SelectListItem> City = null;
        public int CityID { set; get; }

        //return state list
        public List<SelectListItem> GetState()
        {
            SqlDataReader dr = null;
            State = new List<SelectListItem>();
            SqlConnection con = new SqlConnection(Constr);
            con.Open();
            SqlCommand cmd = new SqlCommand("select StateID,StateName from State", con);
            cmd.CommandType = CommandType.Text;
            dr = cmd.ExecuteReader();
           
            State.Add(new SelectListItem { Text = "Select State", Value = "0", Selected = true });
            while (dr.Read())
            {
                State.Add(new SelectListItem { Text = Convert.ToString(dr["StateName"]), Value = Convert.ToString(dr["StateID"]), Selected = true });
            }
            return State;
        }
        //return city list on behalf of state id

        public List<SelectListItem> GetCity(string StateID)
        {
            SqlDataReader dr = null;
            City = new List<SelectListItem>();
            SqlConnection con = new SqlConnection(Constr);
            con.Open();
            SqlCommand cmd = new SqlCommand("select CityID,CityName from TCity  where StateId=" + StateID + "", con);
            cmd.CommandType = CommandType.Text;
            dr = cmd.ExecuteReader();
            City.Add(new SelectListItem { Text = "Select City", Value = "0", Selected = true });
            while (dr.Read())
            {
                City.Add(new SelectListItem { Text = Convert.ToString(dr["CityName"]), Value = Convert.ToString(dr["CityID"]), Selected = true });
            }
            return City;
        }
    }
}

Step 6
Now Right Click on Controller folder at solution explorer add a new Controller (the out put will look like) now click on Controller


 a new window will be open name it to  index. The out put will look like


now click on Add button
Step 8
Write the code in IndexController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CascadingDropDownMVC.Models;
namespace CascadingDropDownMVC.Controllers
{
    public class IndexController : Controller
    {
        //
        // GET: /Index/
        public ActionResult Index()
        {
            StateCity obj = new StateCity();
            ViewBag.State = obj.GetState();
            return View();
        }
        public JsonResult City(string StateID)
        {
            List<SelectListItem> City = new List<SelectListItem>();
            StateCity obj = new StateCity();
            City = obj.GetCity(StateID);
            return Json(City);
        }
    }
}

Step 9

Create a View for this contoller, now right click on Index ActionResult method , a popup window will be open click on Add View  and write the code given below:

@model CascadingDropDownMVC.Models.StateCity
@{
    ViewBag.Title = "Cascading DropdownList in MVC";
}
<style type="text/css">
  .inpt       { border:1px solid #CCC; background:#ffffff; margin:0 0 5px; padding:5px; color:#444444; }
.inpt:hover { -webkit-transition:border-color 0.3s ease-in-out; -moz-transition:border-color 0.3s ease-in-out; transition:border-color 0.3s ease-in-out; border:1px solid #AAA; }
.inpt:focus { border:1px solid #395b77; outline:none; }
</style>
@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
    $(document).ready(function () {
        $("#StateID").change(function () {
            if ($("#StateID").val() != "0") {
                var options = {};
                options.url = "/index/City";
                options.type = "POST";
                options.data = JSON.stringify({ StateID: $("#StateID").val() });
                options.dataType = "json";
                options.contentType = "application/json";
                options.success = function (City) {
                    $("#city").empty();
                    for (var i = 0; i < City.length; i++) {
                        alert(City[i].Value);
                        alert(City[i].Text);
                        $("#city").append('<option value="' + City[i].Value + '">' + City[i].Text + '</option>');
                    }
                    $("#city").prop("disabled", false);
                };
                options.error = function () { alert("Error retrieving city!"); };
                $.ajax(options);
            }
            else {
                $("#city").empty();
                $("#city").prop("disabled", true);
            }
        });
    });
</script>
<h2>Cascading DropdownList in MVC</h2>
<table>
<tr>
<td style="width:50px;"><b>State</b> :</td>
<td>@Html.DropDownListFor(model => model.StateID, new SelectList(ViewBag.State, "Value", "Text"), new { @class = "inpt" })</td>
</tr>
<tr>
<td style="width:50px;"><b>City</b> :</td>
<td>@Html.DropDownList("city", new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", @class = "inpt" })</td>
</tr>
</table>

Now rest of changes we will done in "RouteConfig.cs", At the solution explorer App_Start folder conatin this file

changes in RouteConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace CascadingDropDownMVC
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Index", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


Now Run you application output will look like:

Output: