如何使用Html.DropDownList为默认选项设置值

时间:2009-02-24 13:52:40

标签: asp.net-mvc

我正在使用ASP MVC RC1。

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

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

然而,渲染时,这就是我得到的

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

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

那么如何设置默认选项的值,然后在表单上选中它?

谢谢,Dan

4 个答案:

答案 0 :(得分:21)

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

似乎不可能使用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 }));
    }

编辑:最后,最好的方法是让您的模型获取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" )

答案 1 :(得分:3)

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

Function Create() As ViewResult

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

        Return View()

    End Function

在这种情况下,我碰巧知道1是我想要的默认列表项的id,但可能你可以通过查询选择默认值或者你的船只浮动什么

答案 2 :(得分:1)

您可以添加&#34;选择区域&#34;而不是从视图中的定义传递默认项目。来自控制器的List的第0个索引处的数据。

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

答案 3 :(得分:0)

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

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);
}
相关问题