有条件地将属性添加到EditorFor的好方法

本文关键字:EditorFor 方法 添加 属性 有条件 | 更新日期: 2023-09-27 17:58:42

在我的cshtml文件中有很多像这样的@Html.EditorFor对象:

@Html.EditorFor(m => product.size_L, new { htmlAttributes = new { @class = "form-control size_L calculateOffer acceptIntegerOnly", @tabIndex = "1", @autocomplete = "off" } })

我需要将@readonly = "readonly"属性添加到一些EditorFor对象,但仅限于其中一些对象,并且仅当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" } })
}

但它看起来确实不太好。当我有更多的"可选"属性要添加时,情况会怎样?该代码将进一步扩展。

那么,你能想出一些智能、紧凑的解决方案吗?

有条件地将属性添加到EditorFor的好方法

这是来自内存的,但为了清理我庞大的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"
                }
            });
 }