代码之家  ›  专栏  ›  技术社区  ›  Dan Maharry

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

  •  6
  • Dan Maharry  · 技术社区  · 16 年前

    我正在使用的表单包含一个dropdownlist,我已经将它放在一个视图中,并使用此代码。

    <%= 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> 
    

    我希望选择区域Id选项的值为0,并在默认情况下将其标记为选中,以便与其他值一致,并且我可以验证是否已选择区域,因为它是一个强制值。AreaId是一个整数,因此当我当前单击表单时根本没有接触dropdownlist,MVC抱怨“”不是整数,并给我一个绑定错误。

    那么,如何为默认选项设置一个值,然后在表单上将其选中呢?

    谢谢,丹

    4 回复  |  直到 16 年前
        1
  •  21
  •   dampee    7 年前

    我想你有

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

    :最后,最好的方法是让您的模型获取一个可为null的值,并使用RequiredAttribute将其标记为required。我建议对视图使用视图特定的模型,而不是实体模型。由于该值可为null,如果不选择值就发回,则空字符串可以正常工作。将其设置为必需值将导致模型验证失败,并显示相应的消息,说明该值是必需的。这将允许您按原样使用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" )
    
        2
  •  3
  •   mattsoundworld    13 年前

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

    Function Create() As ViewResult
    
            ViewBag.EmployeeId = New SelectList(db.Employees, "Id", "Name", 1)
    
            Return View()
    
        End Function
    

    在本例中,我碰巧知道1是我想要的默认列表项的id,但您可能可以通过查询或其他方式选择默认值

        3
  •  1
  •   RJC    9 年前

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

        4
  •  0
  •   odyth    7 年前

    我想在多个下拉列表中使用相同的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);
    }