添加项目到@Html.下拉列表选项值和设置默认选择

本文关键字:设置 默认 选择 选项 项目 @Html 下拉列表 添加 | 更新日期: 2023-09-27 18:17:03

我在视图中呈现一个选择列表,如下所示:

@Html.DropDownList("SelectCategory", (SelectList)ViewBag.Categories, "All")

我这样填充它:

ViewBag.Categories = new SelectList(db.Categories, "Id", "Name");
呈现

:

<select id="SelectCategory" name="SelectCategory">
<option value="">All</option>
<option value="1">Fruit</option>
<option value="44">T-Shirts</option>
</select>

问题:

1) All的选项值为空,我如何将我的值放在那里,例如0 ?

2)如何设置@Html.DropDownList的默认选择值

添加项目到@Html.下拉列表选项值和设置默认选择

DropDownList()方法的第三个参数添加了一个带有null值的'label'选项。通常,选项文本类似于"请选择",其目的是迫使用户做出有效的选择。如果选择了标签选项,则提交null值,并且ModelState无效(假设您绑定到的属性是必需的)。

如果您想在<option value="0">All</option>中添加一个额外的选项,那么您需要在传递给视图的SelectList中生成该选项,例如

List<SelectListItem> categories = db.Categories.Select(x => new SelectListItem()
{
    Value = x.Id.ToString(), // assumes Id is not already typeof string
    Text = x.Name
}).ToList();
categories.Insert(0, new SelectListItem(){ Value = "0", Text = "All" }) // Or .Add() to add as the last option
ViewBag.Categories = categories;

和视图中的

(注意,删除第三个参数是你不想要标签选项)
@Html.DropDownList("SelectCategory", (IEnumerable<SelectListItem>)ViewBag.Categories, "Please select")

为了最初"选择"一个选项,您需要在将模型传递给视图之前设置绑定到的属性的值,因此,如果属性SelectCategory的值是"0",则在视图第一次显示时将选择"All"选项。如果是"44",那么"t恤"选项将被选中。如果SelectCategory的值与其中一个选项值不匹配,或者是null,那么将选择第一个选项(因为有些东西必须是)

您可以创建您的选择"by hands"

<select>
@foreach (var item in optionList)
{
    if(myCondition)
    {
        <option value="@item.Value" selected="selected">@item.Text</option> 
    }
    else 
    {
         <option value="@item.Value">@item.Text</option>
    }
} 
</select>

或在视图

中使用Linq
var list = optionsList.Select(x => new SelectListItem { Text = x.Text, Value = x.Value, Selected = myCondition });

,那么你可以在其中一个Html中使用该列表。DropdownList下面是完整的示例

int catId = // Gets the catId to select somehow
IEnumerable<SelectListItem> options = optionsList
    .Select(x => new SelectListItem { 
         Text = x.Text, 
         Value = x.Value, 
         Selected = x.Value == catId
     }); // catId 

然后像这样使用:

 @Html.DropdownList("id-of-the-dropdown", options);