asp.net-mvc 如何使用 Html.DropDownList 为默认选项设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/581805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:21:22  来源:igfitidea点击:

How do I set a value for the default option with Html.DropDownList

asp.net-mvc

提问by Dan Maharry

I'm using ASP MVC RC1.

我正在使用 ASP MVC RC1。

A form I'm using contains a dropdownlist which I have put in a view with this code.

我正在使用的表单包含一个下拉列表,我已将此代码放入视图中。

<%= Html.DropDownList("areaid", (SelectList)ViewData["AreaId"], "Select Area Id")%>

However, when rendered, this is what I get

但是,渲染时,这就是我得到的

<select id="areaid" name="areaid">
   <option value="">Select Area Id</option>
   <option value="1">Home</option>
   ...
</select> 

What I'd like is for the Select Area Id option to have a value of 0 and mark it as selected by default so it is consistent with the other values and I can validate whether or not an area has been chosen as it is a mandatory value. AreaId is an integer so when I currently click the form without touching the dropdownlist at all, MVC complains that "" is not an integer and gives me a binding error.

我想要的是 Select Area Id 选项的值为 0 并将其标记为默认选中,因此它与其他值一致,我可以验证是否选择了一个区域,因为它是强制性的价值。AreaId 是一个整数,所以当我当前单击表单时根本没有触及下拉列表,MVC 会抱怨“”不是一个整数,并给我一个绑定错误。

SO how do I set a value for the default option and then make it selected on the form?

那么如何为默认选项设置一个值,然后在表单上选择它?

Thanks, Dan

谢谢,丹

回答by tvanfosson

I think you have threefour options. First when you are building your SelectList or enumerable of SelectItemList, prepend the selection with your option label and default value. Putting it at the top will make it the default if some other value isn't already chosen in the model. Second, you could build the select (and options) "by hand" in the view using a loop to create the options. Again, prepending your default selection if one isn't supplied in the model. Third, use the DropDownList extension, but modify the value of the first option using javascript after the page is loaded.

我想你有三个四个选项。首先,当您构建 SelectList 或 SelectItemList 的可枚举项时,在选项前面加上选项标签和默认值。如果模型中尚未选择其他值,则将其置于顶部将使其成为默认值。其次,您可以使用循环在视图中“手动”构建选择(和选项)以创建选项。同样,如果模型中没有提供默认选择,请在前面加上默认选择。第三,使用 DropDownList 扩展,但在页面加载后使用 javascript 修改第一个选项的值。

It doesn't seem to be possible to use the DropDownList extension to assign a value to an optionLabel as it is hard-coded to use string.Empty. Below is the relevant code snippet from http://www.codeplex.com/aspnet.

似乎不可能使用 DropDownList 扩展为 optionLabel 分配值,因为它是硬编码的string.Empty。下面是来自http://www.codeplex.com/aspnet的相关代码片段。

    // Make optionLabel the first item that gets rendered.
    if (optionLabel != null) {
        listItemBuilder.AppendLine(ListItemToOption(new SelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false }));
    }

EDIT: Finally, the best way is to have your model take a Nullable value and mark it as required using the RequiredAttribute. I would recommend using a view-specific model rather than an entity model for the view. Since the value is Nullable, the empty string will work fine if posted back without choosing a value. Setting it as a required value will cause the model validation to fail with an appropriate message that the value is required. This will allow you to use the DropdownList helper as is.

编辑:最后,最好的方法是让您的模型采用 Nullable 值并使用 RequiredAttribute 将其标记为需要。我建议为视图使用特定于视图的模型而不是实体模型。由于该值为 Nullable,因此如果在不选择值的情况下回传,则空字符串将正常工作。将其设置为必需值将导致模型验证失败,并显示需要该值的适当消息。这将允许您按原样使用 DropdownList 助手。

public AreaViewModel
{
    [Required]
    public int? AreaId { get; set; }

    public IEnumerable<SelectListItem> Areas { get; set; }
    ...
}

@Html.DropDownListFor( model => model.AreaId, Model.Areas, "Select Area Id" )

回答by mattsoundworld

For MVC3, SelectList has an overload whereby you can define the selected value.

对于 MVC3,SelectList 有一个重载,您可以通过它定义选定的值。

Function Create() As ViewResult

        ViewBag.EmployeeId = New SelectList(db.Employees, "Id", "Name", 1)

        Return View()

    End Function

In this case, I happen to know that 1 is the id of the default list item I want, but presumably you could select the default via query or what ever floats your boat

在这种情况下,我碰巧知道 1 是我想要的默认列表项的 id,但大概您可以通过查询或任何漂浮的船来选择默认值

回答by RJC

Instead of passing the default item from the definition in the View, You can add the "Select Area" data at the 0th index of the List from the controller.

您可以在控制器的列表的第 0 个索引处添加“选择区域”数据,而不是从视图中的定义中传递默认项。

This way the Select Area data has an index value of 0.

这样,选择区域数据的索引值为 0。

回答by odyth

I wanted to use the same SelectList for multiple drop downs and didn't want to duplicate the SelectList in the model so I just added a new Html Extension method that took in a value and set the selected item.

我想对多个下拉列表使用相同的 SelectList 并且不想在模型中复制 SelectList 所以我只是添加了一个新的 Html 扩展方法,该方法接受一个值并设置所选项目。

public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, string value, IList<SelectListItem> selectList, object htmlAttributes)
{
    IEnumerable<SelectListItem> items = selectList.Select(s => new SelectListItem {Text = s.Text, Value = s.Value, Selected = s.Value == value});
    return htmlHelper.DropDownList(name, items, null /* optionLabel */, htmlAttributes);
}