简体   繁体   English

在MVC Html.DropDownListFor中包括默认的“选择选项”

[英]Include default “Select Option” in MVC Html.DropDownListFor

My Model contains an IEnumerable<SelectListItem> and the View contains a DropDownListFor that works fine with the exception that I need to include a default "Select an Option" with a value of -1 in some cases. 我的模型包含一个IEnumerable<SelectListItem> ,而视图包含一个DropDownListFor ,除了在某些情况下需要包含默认值为“ -1”的默认“选择选项”之外,它可以正常工作。

In the Controller: 在控制器中:

model.Items = _context.SomeTable.Select(m => new SelectListItem()
{
    Text = m.SomeName,
    Value = m.SomeId
});

In the View: 在视图中:

@Html.DropDownListFor(
    w => Model.ItemId,
    new SelectList(Model.Items, "Value", "Text", Model.ItemId),
    new { @class = "form-control text-left" })

Between the Controller or View, how can I add the following as the first option and conditionally selected (if ItemId == -1)? 在Controller或View之间,如何添加以下内容作为第一个选项并有条件地选择它(如果ItemId == -1)?

<option value="Select an Item">Select an Item</option>

Since the logic that determines whether there is an option currently selected is in the Controller I would prefer to add this in the Controller - if possible. 由于确定控制器中当前是否存在选项的逻辑位于控制器中,因此我希望将其添加到控制器中(如果可能)。 Or, if i can get the <option ... added in the View and be selected when the Controller passes -1 as ItemId that would work too. 或者,如果我可以在视图中添加<option ... ,并在Controller传递-1作为ItemId时选择它,它也会起作用。

To add a default item you can try 要添加默认项目,您可以尝试

model.Items.Insert(0, new SelectListItem { Text = "Please Select", Value = "-1" });

That will push the item to the top of the select list for you. 这会将项目推到您选择列表的顶部。 Do this after you have called 致电后请执行此操作

model.Items = _context.SomeTable.Select(m => new SelectListItem()
{
    Text = m.SomeName,
    Value = m.SomeId
}).ToList();

It's important that you add a call to ToList() though, so that you are working with a projected list of items, not just the enumerator. 不过,重要的是您要添加一个对ToList()的调用,这样您才能处理项目的计划清单,而不仅仅是枚举器。

There is an override for 'DropDownListFor' that takes an 'optionLabel' as an argument 有一个'DropDownListFor'替代,它带有'optionLabel'作为参数

@Html.DropdownListFor(m => m.id, "select one", Model.selectList, new {})

You might want to check what value that it generates for that option. 您可能要检查它为该选项生成的值。 I think its either 0 or -1 我认为它是0或-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM