@Html.DropDownListFor - 如何将额外的 <option> 添加到列表

@Html.DropDownListFor - How to append extra <option> to list

我的观点如下:

@Html.DropDownListFor(m => m.Category, new SelectList(Model.categories, "Id", "Name", Model.Category), "All", new { @class = "form-control" })

<select name="Category" id="Category">
 <option value="">All</option>
 <option value="1">Debug</option>
 <option value="2" selected="selected">Error</option>
</select>

在我的回购协议中,我得到如下值:

    public IEnumerable<Category> GetCategories()
    {
        return _context.Category.ToList();
    }

如何给 All 一个值 0 而不是空字符串?

有什么方法可以将它附加到我下面的 repo 方法中,因为我想保持我的控制器干净。

public IEnumerable<SelectListItem> GetCategoriesSelectList()
    {

        return _context.Category
             .Select(s => new SelectListItem
             {
                 Value = s.Id.ToString(),
                 Text = s.Name
             }).ToList();


    }

*更新*

我找到了以下助手,但不知道如何使用它:

 public static SelectList AddFirstItem(SelectList origList, SelectListItem firstItem)
    {
        List<SelectListItem> newList = origList.ToList();
        newList.Insert(0, firstItem);

        var selectedItem = newList.FirstOrDefault(item => item.Selected);
        var selectedItemValue = String.Empty;
        if (selectedItem != null)
        {
            selectedItemValue = selectedItem.Value;
        }

        return new SelectList(newList, "Value", "Text", selectedItemValue);
    }

在我看来我有:

 @Html.DropDownListFor(m => m.Category, Helpers.AddFirstItem(new SelectList(Model.categories, "Id", "Name", Model.Category), "All"), null, new { @class = "form-control" })

我应该将什么作为第二个参数传入 - 以上不起作用?

在包含 SelectListItemText = "All"Value = "0" 的控制器中创建您的 SelectList,例如

IEnumerable<SelectListItem> categories = new List<SelectListItem>
{
    new SelectListItem() {Value = "0", Text = "All" }

}.Concat(GetCategories().Select(x => new SelectListItem
{
    Value = x.Id.ToString(),
    Text = x.Name
});

然后将其传递给视图,最好是在视图模型中 属性,但您可以使用 ViewBag

ViewBag.CategoryList = categories;

并在视图中

@Html.DropDownListFor(m => m.Category,(IEnumerable<SelectListItem>)ViewBag.CategoryList, new { @class = "form-control" })

请试试这个:

public IEnumerable<SelectListItem> GetCategoriesSelectList()
{

    return _context.Category
         .Select(s => new SelectListItem
         {
             Value = s.Id.ToString(),
             Text = s.Name
         }).ToList().Add(new SelectListItem() { Text="all",Value="0" });


}