我有以下代码:
public static class HtmlExtendedHelpers
{
public static IHtmlString eSecretaryEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel,TProperty>> ex, object htmlAttributes, bool disabled )
{
if (disabled)
{
htmlAttributes.Add(new { @disabled = "disabled" }); //searching for working code as replacement for this line
}
return htmlHelper.EditorFor(ex, htmlAttributes);
}
}
当禁用= false时它可以工作,当我禁用时,我的所有选择都会失败。然后没有任何htmlAttributes被写入。
变量htmlAttribute具有VALUE(包括htmlAttributes属性:)
htmlAttributes: { class = "form-control" }
这是因为我有一个默认的表单控件类,我想添加一个属性:禁用值禁用。
有谁知道如何正确实现这个?
PS。自Asp.Net MVC 5.1以来,支持htmlAttributes
答案 0 :(得分:5)
您可以使用HtmlHelper.AnonymousObjectToHtmlAttributes
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (disabled)
{
attributes.Add("disabled", "disabled");
}
或者,您可以将disabled
属性作为htmlAttributes
对象的一部分传递,这意味着您根本不需要if
语句。
htmlAttributes: { class = "form-control", disabled = "disabled" }
根据您是否拥有自定义EditorFor
模板,您可能需要更改将html属性传递给EditorFor
函数的方式,因为它接受的参数为additionalViewData
是不一样的。
This article更详细地解释。
如果您使用的是默认模板,则可以在另一个匿名对象中传递html属性:
return htmlHelper.EditorFor(ex, new { htmlAttributes = attributes });
如果您有自定义模板,则需要检索html属性并自己在视图中应用它们:
@{
var htmlAttributes = ViewData["htmlAttributes"] ?? new { };
}
答案 1 :(得分:0)
您可以传递htmlAttributes中的属性,如下所示:
htmlAttributes: { class = "form-control", disbaled="disabled" }
您还可以创建元数据属性,可以在您使用EditorFor的属性上进行修饰。
要创建自己的元数据属性,您可以实现IMetadataAware
接口。