Home > DeveloperSection > Articles > Dropdown list helper for creating dropdown list in ASP.NET MVC3

Dropdown list helper for creating dropdown list in ASP.NET MVC3


ASP.NET MVC ASP.NET MVC 
Ratings:
2 Comment(s)
 20211  View(s)
Rate this:

Dropdown list helper for creating dropdown list in ASP.NET MVC3

In this article I am going to tell you that how to use DropDownList help method in ASP.NET MVC3 for creating simple dropdown list. Here I am using ViewBag object to pass ListItems to dropdown list.

First take a look at Model which I had created for this example.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace DropDownListDemo.Models

{

    public class CityModel

    {

        public string CityName { get; set; }

    }

}

 

Here you can see that I had created one property name CityName which is used to store selected Item from dropdown list.

Now let’s take a look at method signature which is provided by HtmlDropDownList helper.

Html.DropDownList(

    string name,

    IEnumerable<SelectListItem> selectList,

    string optionLabel,

    object htmlAttributes)

 

And the meaning of the parameters:

  • name – the name of the HTML select element, and also the name of the view model property that is bound to the element
  • selectList – the list of options of the select list
  • optionLabel – the text that will be added at the top of the select list. Usually something like “Select …”
  • htmlAttributes – this is in common with all the other html helper. A dictionary or an anonymous type with the html attributes you want to add to the HTML element

All the parameters except the first one are optional: if only the name is provided, the helper will automatically bind the list item. Otherwise if both the name and selectList are provided, the select item will be bound and the select list will be the one supplied with the parameter.

The SelectListItemClass

This class has three properties:

  • string Text – the string that will be displayed as text of the option
  • string Value – the string that will be used as the value of the option
  • bool Selected – whether the option is selected

Now take a look at HomeController which I had created for populating dropdown list.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using DropDownListDemo.Models;

 

namespace DropDownListDemo.Controllers

{

    public class HomeController : Controller

    {

       

        [HttpGet]

        public ActionResult Index()

        {

            //Create a select list item which needs to be bound in

            //dropdown list.

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

 

            //Add city names in city list.

            cityList.Add(new SelectListItem

            {

                Text = "Allahabad",

                Value = "Allahabad"

            });

 

            cityList.Add(new SelectListItem

            {

                Text = "Agra",

                Value = "Agra"

            });

 

            cityList.Add(new SelectListItem

            {

                Text = "Lucknow",

                Value = "Lucknow"

            });

 

            cityList.Add(new SelectListItem

            {

                Text = "Kanpur",

                Value = "Kanpur"

            });

 

            cityList.Add(new SelectListItem

            {

                Text = "Noida",

                Value = "Noida"

            });

 

            //Add city list in ViewBag object.

            ViewBag.CityList = cityList;

           

 

            return View();

        }

 

        [HttpPost]

        public string Index(CityModel model)

        {

            //Return city name which is selected from dropdownlist

            return model.CityName;

        }

 

    }

}

After creating this controller we will need to create a strongly typed view which is look as follows.

@model DropDownListDemo.Models.CityModel

@{

    ViewBag.Title = "Index";

}

<h2>

    Here I am creating a simple dropdown</h2>

@using (Html.BeginForm())

{

    <label>

        Select City</label>

    @Html.DropDownList("CityName", (IEnumerable<SelectListItem>)ViewBag.cityList);

                                                                                

    <p>

        <input type="Submit" value="Submit" />

    </p>

}

Now after creating this view you need to save and build your application. When you execute your application then following output displayed.

Dropdown list helper for creating dropdown list in ASP.NET MVC3

From here when you select city and click on submit button then selected city will appear.

Kanpur

Thanks for reading this article. Please write your valuable comments so that I can improve this article.


asking for code

By satyajit patra on   3 years ago
i need code for state and city cascading dropdownlist in mvc4.
both from database as well as hardcode
thanks in advance

Bind Dropdown in MVC

By Ranjeet Kumar on   3 years ago
In Model

1. Firstly create model class named Course and create property
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace StudentRecord.Models
{
    public class Course
    {

        public int CourseId { get; set; }

        [Display(Name = "Course Name")]
        [Required(ErrorMessage = "Enter Course Name")]
        public string CourseName { get; set; }
    }
}

2. Then create another model class named as u wish. Here we use connection string and stored procedure.but i am using dll class here for connectivity.
 
 public class DbConnectivity
    {
        private static string Config = System.Configuration.ConfigurationManager.ConnectionStrings["strCon"].ConnectionString;

 public List<Course> DropCourse()
        {
            Database db = new SqlDatabase(Config);
            DbCommand dbCommand = db.GetStoredProcCommand("DISPLAYCOURSE");
            List<Course> list = new List<Course>();
            using (IDataReader dataReader = db.ExecuteReader(dbCommand))
            {
                while (dataReader.Read())
                {
                    Course obj = new Course();
                    if (dataReader["Course"] != DBNull.Value)
                    {
                        if (dataReader["Course"] != DBNull.Value) { obj.CourseId = (int)dataReader["Course"]; }
                        if (dataReader["COURSENAME"] != DBNull.Value) { obj.CourseName = (string)dataReader["COURSENAME"]; }
                        list.Add(obj);
                    }
                }
                return list;
            }
        }
}
3.
In Controller
 public ActionResult Drop()
        {
            DbConnectivity dbconnection = new DbConnectivity();
            List<Course> pcontent = new List<Course>();
            {
                //Get all page content from TblHome table
                pcontent = dbconnection.DisplayCourse();

            };
            List<SelectListItem> cityList = new List<SelectListItem>();
            //List<string> items = new List<string>();
            foreach (var item in pcontent)
            {
                cityList.Add(new SelectListItem
                {
                    Text = item.CourseName,
                    Value = item.CourseId.ToString()
                });
            }
          
            ViewBag.CityList = cityList;
            return View();


            //return View(pcontent);
        }


In  public ActionResult Drop()
        {
            DbConnectivity dbconnection = new DbConnectivity();
            List<Course> pcontent = new List<Course>();
            {
                //Get all page content from TblHome table
                pcontent = dbconnection.DisplayCourse();

            };
            List<SelectListItem> cityList = new List<SelectListItem>();
            //List<string> items = new List<string>();
            foreach (var item in pcontent)
            {
                cityList.Add(new SelectListItem
                {
                    Text = item.CourseName,
                    Value = item.CourseId.ToString()
                });
            }
          
            ViewBag.CityList = cityList;
            return View();


            //return View(pcontent);
        }

4.
In View

@model StudentRecord.Models.Course

@{
    ViewBag.Title = "Drop";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Drop</h2>


<fieldset>
    <legend>Course</legend>

    <div class="display-label">CourseName</div>
    <div class="display-field">
       @Html.DropDownList("CourseName", (IEnumerable<SelectListItem>)ViewBag.cityList,"Select Course")
    </div>
    </fieldset>
 @using (Html.BeginForm())


<p>
   <input type="Submit" value="Submit" />

    </p>

}

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

Follow MindStick