public IEnumerable<SelectListItem> GetList(int? ID)
{
return from s in db.List
orderby s.Descript
select new SelectListItem
{
Text = s.Descript,
Value = s.ID.ToString(),
Selected = (s.ID == ID)
};
}
Run Code Online (Sandbox Code Playgroud)
我将上面的内容返回到视图并填充一个DropDownList
.我想SelectListItem (0, "Please Select..")
在返回到视图之前向上面的linq结果添加一个默认值.这可能吗?
Meh*_*ari 31
return new[] { new SelectListItem { Text = ... } }.Concat(
from s in db.List
orderby s.Descript
select new SelectListItem
{
Text = s.Descript,
Value = s.ID.ToString(),
Selected = (s.ID == ID)
});
Run Code Online (Sandbox Code Playgroud)
Ste*_*ock 21
当您使用ASP.NET MVC时,您可以在视图中通过为HtmlHelper的DropDownField方法的optionLabel参数指定值来执行此操作 - 例如:
htmlHelper.DropDownList("customerId", selectList, "Select One");
Run Code Online (Sandbox Code Playgroud)
将这种类型的代码放在UI层中可能比在数据层中使用它更合适.这样做的一个缺点是,您的选择框将具有空字符串值,而不是"选择一个"选项的"0",但这不是真正的问题,因为如果您的控制器操作可以将其视为空值方法可以接受相关参数的可空int - 例如
public ActionResult DoSomething(int? customerId)
{
if(customerId != null)
{
// do something with the value
}
}
Run Code Online (Sandbox Code Playgroud)