@ Html.DropDownList无法添加表单控件类

时间:2015-08-09 13:11:48

标签: asp.net-mvc razor drop-down-menu form-control

我需要在DropDownList中添加一个类,使它看起来更具代表性。因此,我使用下面的代码htmlAttribute

@Html.DropDownList("DepartmentId", "Select a Department:", htmlAttributes: new { @class = "form-control" })

我收到错误,因为它说:

does not contain a definition for 'DropDownList' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, string)' has some invalid arguments

有人可以教我如何添加表单控件类来做DropDownList吗?

正在运行的代码:

@Html.DropDownList("DepartmentId", null, htmlAttributes: new { @class = "form-control" })

1 个答案:

答案 0 :(得分:1)

DropDownList没有重载,允许您同时指定默认选项和HTML属性。但是DropDownListFor确实如此。

您如何使用选项填充下拉列表?如果您在控制器操作中执行服务器端操作,则可以(并且可能应该)使用DropDownListFor

@model DepartmentViewModel
...
@Html.DropDownListFor(model => model.DepartmentId, Model.Departments, "Select a Department:", new { @class = "form-control" })

您的视图模型类将如下:

public class DepartmentViewModel {
    ...
    public int DepartmentId { get; set; }
    public IEnumerable<SelectListItem> Departments { get; set; }
    ...
}

在你的控制器动作中:

public ActionResult Index() {
    ...
    var model = new DepartmentViewModel();
    model.Departments = new List<SelectListItem> {
        new SelectListItem { Value = "1", Text = "First Department"},
        new SelectListItem { Value = "2", Text = "Second Department"}
    };
    ...
    return View(model);
}

但是如果您通过javascript / jquery使用值填充下拉列表,那么使用常规HTML语法就会很容易:

<select name="DepartmentId" id="DepartmentId" class="form-control">
    <option value="">Select a Department:</option>
<select>