Home > DeveloperSection > Beginner > DropDownList in ASP.NET MVC

DropDownList in ASP.NET MVC


ASP.NET MVC Mvc4  Dropdown 
Ratings:
0 Comment(s)
 3980  View(s)
Rate this:

DropDownList in ASP.NET MVC

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

 

Step 1

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

Give application name

Step 2

Select Empty template then click OK.

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

{

    public class StudentModel

    {

        public IList<SelectListItem> StateNames { get; set; }

        public IList<SelectListItem> DistrictNames { get; set; } 

    }

}

Step 4

Create a .edmx file and connect with the database.



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

{

    public class HomeController : Controller

    {

       

        NiitEntities db = new NiitEntities();

 

        public ActionResult Index()

        {

            List<SelectListItem> stateName = new List<SelectListItem>();

            StudentModel stumodel = new StudentModel();

            List<State> states = db.States.ToList();

            states.ForEach(x =>

            {

                stateName.Add(new SelectListItem { Text = x.StateName, Value = x.StateID.ToString() });

            });

            stumodel.StateNames = stateName;

            return View(stumodel);

        }

        [HttpPost]

        public ActionResult GetDistrict(string stateId)

        {

            int statId;

            List<SelectListItem> districtNames = new List<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(new SelectListItem { Text = x.DestrictName, Value = x.DestrictID.ToString() });

                });

            }

            return Json(districtNames, JsonRequestBehavior.AllowGet);

        } 

 

    }

}

 

Index.cshtml

@model MvcDropDownDemo.Models.StudentModel

@{

    ViewBag.Title = "Index";

}

 

<link href="~/Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

<script src="~/Scripts/jquery-2.1.1.min.js"></script>

<h2 class="text-center">DropDownList</h2>

<div class="container" style="width:50%;margin:0 auto;">

    <div class="table-responsive">

        <table class="table table-bordered table-striped">

            <thead>

                <tr class="success">

                    <th class="text-center">State</th>

                    <th class="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, new List<SelectListItem>(), "--Select--", new {@class="form-control", @id = "ddlDistrict" }) </td>

                </tr>

            </tbody>

        </table>

    </div>

</div>

<script type="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:

 

public IList<SelectListItem> StateNames { get; set; }

public IList<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 NiitEntities object, in this object all the related tables exist.

NiitEntities db = new NiitEntities();

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(new SelectListItem { 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:


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


Don't want to miss updates? Please click the below button!

Follow MindStick