Nic*_*icy 2 asp.net asp.net-mvc editorfor razor asp.net-mvc-5.1
我有以下代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
它在禁用= false时工作,当我禁用时,我的所有备选方案都失败.然后没有任何htmlAttributes被写入.
变量htmlAttribute具有VALUE(包括htmlAttributes属性:)
htmlAttributes: { class = "form-control" }
Run Code Online (Sandbox Code Playgroud)
这是因为我有一个默认的表单控件类,我想添加一个属性:禁用值禁用.
有谁知道如何正确实现这一点?
PS.从Asp.Net MVC 5.1开始,就支持htmlAttributes
您可以使用 HtmlHelper.AnonymousObjectToHtmlAttributes
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (disabled)
{
attributes.Add("disabled", "disabled");
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以将disabled属性作为htmlAttributes对象的一部分传递,这意味着您根本不需要该if语句.
htmlAttributes: { class = "form-control", disabled = "disabled" }
Run Code Online (Sandbox Code Playgroud)
根据您是否有自定义EditorFor模板,您可能需要更改将html属性传递给EditorFor函数的方式,因为它接受的参数additionalViewData不同.
本文将更详细地解释.
如果您使用的是默认模板,则可以在另一个匿名对象中传递html属性:
return htmlHelper.EditorFor(ex, new { htmlAttributes = attributes });
Run Code Online (Sandbox Code Playgroud)
如果您有自定义模板,则需要检索html属性并在视图中自行应用它们:
@{
var htmlAttributes = ViewData["htmlAttributes"] ?? new { };
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1539 次 |
| 最近记录: |