Asp.net mvc @Html.DropDownList无法添加表单控件类
我需要在DropDownList中添加一个类,使它看起来更美观。因此,我将下面的代码与Asp.net mvc @Html.DropDownList无法添加表单控件类,asp.net-mvc,razor,drop-down-menu,form-control,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 exte
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属性<但是,code>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 int DepartmentId{get;set;}
公共IEnumerable部门{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);
}
public ActionResult Index(){
...
var模型=新部门视图模型();
model.Departments=新列表{
新建SelectListItem{Value=“1”,Text=“First Department”},
新建SelectListItem{Value=“2”,Text=“第二部门”}
};
...
返回视图(模型);
}
但是,如果您通过javascript/jquery用值填充下拉列表,那么使用常规HTML语法也同样容易:
<select name="DepartmentId" id="DepartmentId" class="form-control">
<option value="">Select a Department:</option>
<select>
选择一个部门:
如果您已经有了正在工作的代码,还有问题吗?没有超负荷的DropDownList()
接受2个字符串参数和IDictionary
。第二种方法之所以有效,是因为有一个重载,其第二个参数为IEnumerable
,您将其传递为null
,这种方法不是将值硬编码到DropDownList中吗?我有一个sql server数据库,我想用它填充我的DropDownList。是的,你说得对。硬编码值只是演示如何填充视图模型的一种方式。实际上,您的部门列表将使用类似ORM的实体框架或Dapper从数据库中动态检索。这很奇怪,因为今天我使用的是@Html.DropDownList(“storeSelect”,new SelectList(Model.SelectableStores),“-选择存储-”,new{@class=“form control”}
,它工作得很好!
<select name="DepartmentId" id="DepartmentId" class="form-control">
<option value="">Select a Department:</option>
<select>