一、非强类型:
Controller:
ViewData["AreId"] = from a in Table
select new SelectListItem {
Text=a.AreaName,
Value=a.AreaId.ToString()
};
View:
@Html.DropDownList("AreId")
还可以给其加上一个默认选项:@Html.DropDownList("AreId", "请选择");
二、强类型:
DropDownListFor常用的是两个参数的重载,第一参数是生成的select的名称,第二个参数是数据,用于将绑定数据源至DropDownListFor
Modle:
public class SettingsViewModel
{
Repository rp =new Repository();
public string ListName { get; set; }
public IEnumerable<SelectListItem> GetSelectList()
{
var selectList = Table.Select(a => new SelectListItem {
Text=a.AreaName,
Value=a.AreaId.ToString()
});
return selectList;
}
}
Controller:
public ActionResult Index()
{
return View(new SettingsViewModel());
}
View:
@model Mvc3Applicationtest2.Models.SettingsViewModel
@Html.DropDownListFor(m=>m.ListName,Model.GetSelectList(),"请选择")
转载于:https://www.cnblogs.com/shenbing/p/5390713.html
本文详细介绍了在ASP.NET MVC中如何使用非强类型和强类型方式创建下拉列表(DropDownList)。通过Controller向View传递数据,并利用HtmlHelper扩展方法在View中渲染下拉列表,包括添加默认选项的方法。
1109

被折叠的 条评论
为什么被折叠?



