Monday, April 19, 2021

MVC DropDownList Example using SelectListItem class

Create ASP.NET MVC Framework 4.7.2 based application.

Step1: Create Controllers/HomeController

using System.Collections.Generic;
using System.Web.Mvc;

namespace MVCDropdown1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            List list = new List();

            list.Add(new SelectListItem { Value = "1", Text = "Ajeet Kumar", Selected = true });
            list.Add(new SelectListItem { Value = "2", Text = "Rajeev", Selected = false });
            list.Add(new SelectListItem { Value = "3", Text = "Minakshi", Selected = false });

            ViewBag.data = new SelectList(list);
            ViewBag.data2 = new SelectList(list, "Value", "Text");

            return View();


        }
    }
}
STEP2: Create Views/Home/Index

<h2>DropDownList</h2>

@Html.DropDownList("Dropdown", ViewBag.data as SelectList)
<br />
<br />
<br />
@Html.DropDownList("Dropdown", ViewBag.data2 as SelectList)
Output:




No comments:

Post a Comment

Hot Topics