如何避免重复内联条件来定义 Html.EditorFor() 的 htmlAttributes

How do I avoid repetitive inline conditionals for defining htmlAttributes of Html.EditorFor()

我正在构建一个表单,我必须继续使用内联条件来添加 readonly html 属性:

@Html.LabelFor(model => model.EventDate)
<div class="row">
    <div class="col-xs-3">
        @Html.EditorFor(model => model.EventDate, new
        {
            htmlAttributes = Model.IsEditorReadOnly ?
                (object)new { @class = "form-control input-lg", @type = "date", @readonly = "readonly" } :
                (object)new { @class = "form-control input-lg", @type = "date" }
        })
    </div>
</div>
@Html.ValidationMessageFor(model => model.EventDate)

您不能仅对 @readonly 属性 的值使用条件,因为即使它设置为 null,它也会作为 readonly="" 呈现给客户端] 这足以让浏览器将该字段设置为只读。

必须有比为每个表单元素添加一个属性的内联条件更好的方法,对吗?

感谢Steven Muecke for all the assistance (give him all your up-votes above in the comments and at his ). Here's the solution

对于具有此 属性 的模型:

[Display(Name = "Event Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[Range(typeof(DateTime), "01-01-2010", "12-31-2030")]
public DateTime? EventDate { get; set; }

创建此扩展方法:

public static IHtmlString ReadOnlyEditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object
htmlAttributes = null, bool isReadOnly = false)
{
    IDictionary<string, object> attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    if (isReadOnly)
    {
        attributes.Add("readonly", "readonly");
    }

    return html.EditorFor(expression, new { htmlAttributes = attributes });
}

然后像这样在视图中使用它:

@Html.ReadOnlyEditorFor(model => model.EventDate, 
    new { @class = "form-control input-lg", @type = "date" }, 
    Model.IsEditorReadOnly)

模型的所有 属性 元数据都将出现在页面上调用的 第一个 实例中。结果 html 将如下所示:

<input class="form-control input-lg text-box single-line" data-val="true" data-val-date="The field Event Date must be a date." data-val-range="The field Event Date must be between 1/1/2010 12:00:00 AM and 12/31/2030 12:00:00 AM." data-val-range-max="12/31/2030 00:00:00" data-val-range-min="01/01/2010 00:00:00" id="EventDate" name="EventDate" type="date" value="08-01-2015" />