Quantcast
Channel: MVC – AuthorCode
Viewing all articles
Browse latest Browse all 10

MVC 4 Exercise-1: Bind dropdownlist based on what is selected in another dropdownlist

$
0
0

Introduction: Create a MVC 4 page that will contains two dropdownlist controls. The first dropdownlist will be for State list and second will contains the City list on the basis of the selected state.

bind select based on another select

Exercise: After selecting an option from a dropdownlist the other dropdownlist should update based on what is selected, with ajax/jquery.

Data table you can use:

Script to create the table tblCity:

CREATE TABLE [dbo].[tblCity](
[city_id] [int] IDENTITY(1,1) NOT NULL,
[city_name] [nvarchar](50) NULL,
[state_id] [int] NULL,
[state_name] [nvarchar](50) NULL,
CONSTRAINT [PK_tblCity] PRIMARY KEY CLUSTERED
(
[city_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]

city_id city_name state_id state_name
1 Merrut 1 UP
2 Ghaziabad 1 UP
3 Lucknow 1 UP
4 Bhopal 2 MP
5 Abc 2 MP

Solution

First i have created a table tblCity using above script and put the some data(as shown above in the table) in the used database. Update my entity model and start work. After updating the model you can see the the tblCity.cs in the < your model >.edmx – > < your model >.tt.

//-----------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior
//    in your application.
//    Manual changes to this file will be overwritten if the 
//    code is regenerated.
// </auto-generated>
//-----------------------------------------------------------------
 
namespace MvcApplication1
{
    using System;
    using System.Collections.Generic;
 
    public partial class tblCity
    {
        public int city_id { get; set; }
        public string city_name { get; set; }
        public Nullable<int> state_id { get; set; }
        public string state_name { get; set; }
    }
}

This is the view named ‘EmployeeSearch.cshtml’ that contains a two select element. If you use the Html.DropDownList or Html.DropDownListFor controls to show the drop-down list than view always renders as an html select element.

The first select element will contains the name of the states and another is for all cities according to selected state.

@model IEnumerable<MvcApplication1.tblCity>
@{
    ViewBag.Title = "EmployeeSearch";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>EmployeeSearch</h2>
@using (Html.BeginForm())
{
    <div class="input-group">
        <span class="input-group-addon">State</span>
        <select id="state" name="state">
            <option id="" value="oras">-- Choose --</option>
            @foreach (var c in Model.Select(s => s.state_name).Distinct())
            { <option id="@c" value="@c">@c</option> }
        </select>
    </div>
 
    <div class="input-group">
        <span class="input-group-addon">City</span>
        <select id="city" name="city">
            <option id="" value="oras">-- Choose --</option>
 
        </select>
    </div>    
}
<script>
    $('#state').change(function (e) {
        e.preventDefault();
        var url = '@Url.Action("GetCityNames")';
        var statename = $('#state option:selected').text();
        $.post(url, { stateNm: statename }, function (data) {
            var items = [];
            items.push("<option>--Choose--</option>");
            $.each(data, function () {
                items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
            });
            $("#city").html(items.join(' '));
        });
   });
</script>

Here’s how to get the all Cities from the database table. Create a ActionResult post method in your controller to get the Json object that will contains the all cities according to selected state.

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        private EmployeeDatabaseEntities _dbcontext = new EmployeeDatabaseEntities();
        public ActionResult EmployeeSearch()
        {
            Response.CacheControl = "no-cache";
            _dbcontext = new EmployeeDatabaseEntities();
            var model = _dbcontext.tblCities;
            return View("EmployeeSearch", model.ToList<tblCity>());
        }
 
        [HttpPost]
        public ActionResult GetCityNames(string stateNm)
        {
            IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
            _dbcontext = new EmployeeDatabaseEntities();
            if (!string.IsNullOrEmpty(stateNm))
            {
                cityList = (from m in _dbcontext.tblCities where m.state_name == stateNm select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.city_name, Value = m.city_id.ToString() });
            };
            var result = Json(new SelectList(cityList, "Value", "Text"));
            return result;
        }
}

I hope this is helpful solution to bind the select according to another select in MVC 4. I will add more explanation on this solution in near future. This solution has published on the urgent demand of our user ‘Dan Radic’.


Viewing all articles
Browse latest Browse all 10

Trending Articles