Part 6 - Generating a dropdownlist control in mvc using HTML helpers

To generate a dropdownlist, use DropDownList html helper. A dropdownlist in MVC is a collection of SelectListItem objects. Depending on your project requirement you may either hard code the values in code or retrieve them from a database table. In this video, we will discuss both the approaches. 

Generating a dropdownlist using hard coded values: We will use the following overloaded version of "DropDownList" html helper.
DropDownList(string name, IEnumerable<SelectListItem> selectList, string optionLabel)

The following code will generate a departments dropdown list. The first item in the list will be "Select Department".
@Html.DropDownList("Departments"new List<SelectListItem>

    new SelectListItem { Text = "IT", Value = "1", Selected=true},
    new SelectListItem { Text = "HR", Value = "2"},
    new SelectListItem { Text = "Payroll", Value = "3"}
}, "Select Department") 

The downside of hard coding dropdownlist values with-in code is that, if we have to add or remove departments from the dropdownlist, the code needs to be modified. 

In most cases, we get values from the database table. For this example, let's use entity framework to retrieve data. Add ADO.NET entity data model. 

To pass list of Departments from the controller, store them in "ViewBag"
public ActionResult Index()
{
    // Connect to the database
    SampleDBContext db = new SampleDBContext();
    // Retrieve departments, and build SelectList
    ViewBag.Departments = new SelectList(db.Departments, "Id""Name");
            
    return View();
}

Now in the "Index" view, access Departments list from "ViewBag"
@Html.DropDownList("Departments""Select Department")         //第一个参数要和ViewBag中SelectList对象一致


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值