1

我需要向 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" })
4

1 回答 1

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>
于 2015-08-10T01:49:27.003 回答