我的cshtml文件中有很多@Html.EditorFor
个像这样的对象:
@Html.EditorFor(m => product.size_L, new { htmlAttributes = new { @class = "form-control size_L calculateOffer acceptIntegerOnly", @tabIndex = "1", @autocomplete = "off" } })
我需要为某些EditorFor对象添加@readonly = "readonly"
属性,但仅针对其中一些对象,仅在product.enableReadonly == true
时。
当然,我可以这样做:
@if (product.enableReadonly)
{
@Html.EditorFor(m => product.size_L, new { htmlAttributes = new { @class = "form-control size_L calculateOffer acceptIntegerOnly", @tabIndex = "1", @autocomplete = "off" } })
}
else
{
@Html.EditorFor(m => product.size_L, new { htmlAttributes = new { @class = "form-control size_L calculateOffer acceptIntegerOnly", @tabIndex = "1", @autocomplete = "off", @readonly="readonly" } })
}
但它看起来并不好看。当我有更多那些"可选"要添加的属性?代码会扩展得更多。
那么,您能想到一些智能,紧凑的解决方案吗?
答案 0 :(得分:0)
这是来自内存,但是为了清理我的巨大EditorFor
调用,我创建了一些这样的重载方法:
public static MvcHtmlString EditorFor<TModel, TItem>(this HtmlHelper<TModel> html, Expression<Func<TModel, TItem>> expr, bool readOnly)
{
if (readOnly)
{
return html.EditorFor(expr, new
{
htmlAttributes = new
{
@class = "form-control size_L calculateOffer acceptIntegerOnly",
tabIndex = "1",
autocomplete = "off",
@readonly = "readonly"
}
});
}
return html.EditorFor(expr, new
{
htmlAttributes = new
{
@class = "form-control size_L calculateOffer acceptIntegerOnly",
tabIndex = "1",
autocomplete = "off"
}
});
}