articles

Home / DeveloperSection / Articles / DropDownList in ASP.NET MVC

DropDownList in ASP.NET MVC

Anonymous User12128 19-Jan-2015

Hi everyone in this article I’m explaining about DropDownList in mvc.

Description:

In a Web Form, a DropDownList is common and time to time we need to provide the functionality of cascading between dropdownlists. Today in this article we will learn how to populate a dropdownlist and cascade between those dropdownlists.

How to populate a Dropdownlist in ASP.Net MVC

In this article we have a School database with the following 2 tables.

  • State
  • District

DropDownList in ASP.NET MVC

 

Step 1

Open Visual Studio then select File >> New >> Project then select ASP.Net MVC 4

Web Application.

DropDownList in ASP.NET MVC

Give application name

Step 2

Select Empty template then click OK.

DropDownList in ASP.NET MVC

Step 3

Select the Model folder then create a new Model class.

StudentModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MvcDropdown.Models
{
    publicclassStudentModel
    {
        publicIList<SelectListItem> StateNames { get; set; }
        publicIList<SelectListItem> DistrictNames { get; set; } 
    }
}

Step 4

Create a .edmx file and connect with the database.

DropDownList in ASP.NET MVC

Step 5

Create a new Controller. In this article I create HomeController.cs. 

HomeController.cs

using MvcDropDownDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MvcDropDownDemo.Controllers
{
    publicclassHomeController : Controller
    {
       
        NiitEntities db = newNiitEntities();
 
        publicActionResult Index()
        {
            List<SelectListItem> stateName = newList<SelectListItem>();
            StudentModel stumodel = newStudentModel();
            List<State> states = db.States.ToList();
            states.ForEach(x =>
            {
                stateName.Add(newSelectListItem { Text = x.StateName, Value = x.StateID.ToString() });
            });
            stumodel.StateNames = stateName;
            return View(stumodel);
        }
        [HttpPost]
        publicActionResult GetDistrict(string stateId)
        {
            int statId;
            List<SelectListItem> districtNames = newList<SelectListItem>();
            if (!string.IsNullOrEmpty(stateId))
            {
                statId = Convert.ToInt32(stateId);
                List<District> districts = db.Districts.Where(x => x.StateID == statId).ToList();
                districts.ForEach(x =>
                {
                    districtNames.Add(newSelectListItem { Text = x.DestrictName, Value = x.DestrictID.ToString() });
                });
            }
            return Json(districtNames, JsonRequestBehavior.AllowGet);
        } 
 
    }
}

 

Index.cshtml

@model MvcDropDownDemo.Models.StudentModel
@{
    ViewBag.Title = "Index";
}
 
<linkhref="~/Content/bootstrap/css/bootstrap.min.css"rel="stylesheet"/>
<scriptsrc="~/Scripts/jquery-2.1.1.min.js"></script>
<h2class="text-center">DropDownList</h2>
<divclass="container"style="width:50%;margin:0auto;">
    <divclass="table-responsive">
        <tableclass="table table-bordered table-striped">
            <thead>
                <trclass="success">
                    <thclass="text-center">State</th>
                    <thclass="text-center">Destrict</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>@Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--", new {@class="form-control", @id = "ddlState" })</td>
                    <td>@Html.DropDownListFor(x => x.DistrictNames, newList<SelectListItem>(), "--Select--", new {@class="form-control", @id = "ddlDistrict" }) </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
<scripttype="text/javascript">
    $(document).ready(function () {
        $('#ddlState').change(function () {
            $.ajax({
                type: "post",
                url: "/Home/GetDistrict",
                data: { stateId: $('#ddlState').val() },
                datatype: "json",
                traditional: true,
                success: function (data) {
                    var district = "<select id='ddlDistrict'>";
                    district = district + '<option value="">--Select--</option>';
                    for (var i = 0; i < data.length; i++) {
                        district = district + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
                    }
                    district = district + '</select>';
                    $('#District').html(district);
                }
            });
        });
    });
</script>

 

Understand the Code

In Studentmodel we have the following 2 properties:

 

publicIList<SelectListItem> StateNames { get; set; }
publicIList<SelectListItem> DistrictNames { get; set; }

Here we are using the SelectListItem class, this class has the following 3 properties: 

  1. Selected: This is a bool type to show in a dropdown (as selected) true or false by

default.

2-Text: This is a string type, for the dropdown text.

3-Value: This is string type for the value of the dropdown

If you notice in the dropdownlist, we also need the same properties. For this reason

we are using SelectListItem in a Ilist. 

 

In the preceding code we create the NiitEntitiesobject, in this object all the related

tables exist.

NiitEntities db = newNiitEntities();
List<State> states = db.States.ToList();
In the preceding line of code, all the related data of the State tables comes into the State list object.
states.ForEach(x =>
            {
                stateName.Add(newSelectListItem { Text = x.StateName, Value = x.StateID.ToString() });
            });

 

Now it is time to add entity data into the Text and value properties, the all

collection will be stored into the stateNames object.

The preceding code shows the model data in View. Now to understand how it

works.

@Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--", new {@class="form-control", @id = "ddlState" })

Look at the preceding code, we used here, @Html helper classes for creating a


DropDownList. In the DropDownListFor helper class we used 4 parameters.

  1. x=>x.StateNames: For getting the values of the collection from the entity.

  2. Model.StateNames: Collections of states.

  3. “—Select--”: Default value, when the dropdown list will be populated.

  4. new {@id=”ddlState”}: In this part we can define an id, class and name for the

control.

How to do cascading between two dropdownlists.

Output:

DropDownList in ASP.NET MVC


In my previous post i'll explain about Crud Operation in ASP.NET Using SQLite Database


Updated 10-Aug-2020
I am a content writter !

Leave Comment

Comments

Liked By