MVC 5中<select>的默认选项</select>

时间:2015-01-27 11:46:19

标签: html asp.net-mvc twitter-bootstrap-3 asp.net-mvc-5

我在ASP.NET MVC 5应用程序中使用这样的<select>

<div class="form-group">
  <label for="sel1" class="text-primary">Select Static Analysis Tool</label>
  <select class="form-control" name="ToolName" id="sel1" required>
    @foreach(var item in ViewBag.ToolList)
    {
      <option>@item</option>
    }
  </select>
  <input type="submit" value="Submit" class="btn btn-default btn-primary btn-lg" />
</div>

我想在Please Select菜单中添加<select>等默认文字。我怎么能得到它?

2 个答案:

答案 0 :(得分:2)

您可以使用MVC的html帮助程序简化代码并使用强类型模型绑定

假设你的模型属性是

[Display(Name = "Select Static Analysis Tool")]
[Required]
public string ToolName { get; set; }

然后在视图中

@Html.LabelFor(m => m.ToolName, new { @class = "text-primary" })
@Html.DropDownListFor(m => m.ToolName, new SelectList(ViewBag.ToolList), "-Please select-", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.ToolName)

将为select

生成以下html
<select class="form-control" data-val="true" data-val-required="The Name field is required." id="ToolName" name="ToolName">
  <option value>-please select-</option>
  <option>Tool Name 1</option>
  <option>Tool Name 2</option>
  ....
</select>

请注意,第一个选项的值为null,因此如果选择了第一个选项,验证将失败。

如果你想进一步减少这3行,你可以考虑this answer

中的选项

答案 1 :(得分:1)

在评论中回应Skelly的链接(以及this comment也是如此),我提醒您,这不是<select>列表的设计工作方式。标签将用于相同的目的,并为此而设计。如果你以这种方式前进,你就不得不开始提问this

等问题
  

“用户可以选择请选择并提交。如何停止用户   这样做?“

现在事情看起来有点多了。

无论如何,我认为这是错误的做事方式,但这就是我要做的。首先,我使用ViewModel(而不是ViewBag)并将<select>列表合并到其中。这样,您可以使用HTML帮助程序:我认为这是在MVC5中创建SelectList的更正统的方法。

public class ToolViewModel {
    public ToolDropdownList ToolDropdownList { get; set; }
    public string SelectedTool { get; set; }
    // ...
}

public class ToolDropdownList {
    public List<SelectListItem> Tools { get; set; }
}

在使用ToolViewModel ViewModel呈现视图之前,必须使用ToolDropdownList填充SelectListItem。其中每个都代表选择列表中的工具,具有TextValueSelected属性。

您可以在此处添加Please select SelectListItem。

然后我使用HTML帮助器渲染视图,并使用Bootstrap类装饰助手。

<div class="form-group">
    @Html.LabelFor(m => m.SelectedTool, new { @class="text-primary" })
    @Html.DropDownListFor(m => m.SelectedTool,
        new SelectList(Model.ToolDropdownList.Tools, "Value", "Text"),
        new { @class = "form-control", @id = "sel1", @required = "required" })
</div>

如果您仍然 reeeeally 想要允许用户提交选择了Please select...的表单,您可以选择某种特殊客户端或服务器端验证规则来允许此操作。