将自定义文本添加到MVC 5的下拉列表中
本文关键字:下拉列表 MVC 自定义 文本 添加 | 更新日期: 2023-09-27 18:13:09
我有一个下拉列表,我想添加到MVC 5中的_Layout.cshtml页面中。这是从我的数据库中的参考数据返回的——它是针对CarTypes的。有4种不同类型的车型可供选择-轿车、4X4、Estate和掀背车。
我创建了一个CarTypesViewModel,如下所示:
public IEnumerable<SelectListItem> CarTypesList { get; set; }
public string SelectedCarType { get; set; }
然后我有一个观点:
@using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Get))
{
//Just a html div here perhaps?
@Html.DropDownListFor(model => model.SelectedCarType, Model.CarTypesList)
}
在布局中,我有以下内容:
<li id="selectedcar">@Html.Action("Index", "CarTypes")</li>
然后转到我的CarTypes控制器中的此操作:
var model = new CarTypesViewModel
{
CarTypesList= products.Select(p => new SelectListItem
{
Value = p.Id.ToString(CultureInfo.InvariantCulture),
Text = p.Name
})
};
return View(model);
这是将数据返回到下拉列表。然而,我真正想要的是一个值显示为"请选择你的汽车类型"作为列表中的第一项-由于我不想将其作为值存储在我的数据库中,实现这一点的最佳方法是什么?
@Html.DropDownListFor(model => model.SelectedCarType,
new SelectList(Model.CarTypesList, "Value", "Text"),
"--- Please Select Your Car Type ---",
new { @class = "form-control" }
)
将optionLabel
参数传递给DropDownListFor
。
请参阅:http://msdn.microsoft.com/en-us/library/ee703561(v=vs.118(.aspx
@using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Get))
{
//Just a html div here perhaps?
@Html.DropDownListFor(model => model.SelectedCarType, Model.CarTypesList, "Please Select Your Car Type")
}
这应该可以做到。(将自定义文本添加为第3个元素。(