以下内容允许您指定htmlAttribute以获取添加到< select>的其他html属性。项目
public IHtmlString DropDownList(string name, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes);
public IHtmlString DropDownList(string name, IEnumerable<SelectListItem> selectList, object htmlAttributes);
我使用了以下内容,从关于SO和其他问题的问题中得到了很好的效果:
<fieldset name="vehicleIdFieldSet">
<label for="vehicleSelectControl">Choose Vehicle</label>
@{
var htmlAttributes = new { id = "vehicleSelectControl",
style = "font-size:24px;",
};
string string_htmlAttributes = "";
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
{
string_htmlAttributes += string.Format("{0}=\"{1}\" ", property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
}
}
@Html.DropDownList("vehicleId", listVehicles, string_htmlAttributes)
@Html.ValidationMessage("vehicleId")
</fieldset>
我想在属性中添加Validation.ClassFor("vehicleId")
。我似乎无法使其工作,部分原因是当属性值为null时,htmlAttribute无法实例化。另外因为class
是保留字,但我想我有一个解决方法。
不起作用:ClassFor返回null
var htmlAttributes = new { id = "vehicleSelectControl",
style = "font-size:24px;",
@class = Validation.ClassFor("vehicleId").ToString()
不起作用:仍然为空
string className = Validation.ClassFor("vehicleId").ToString();
var htmlAttributes = new { id = "vehicleSelectControl",
style = "font-size:24px;",
@class = className
};
不能工作:仍然无效,不应该
string className = (String.IsNullOrEmpty(Validation.ClassFor("vehicleId").ToString())) ? "" : Validation.ClassFor("vehicleId").ToString();
var htmlAttributes = new { id = "vehicleSelectControl",
style = "font-size:24px;",
@class = className
};
我应该放弃,还是有办法让我的&lt; select&gt;通过验证风格?