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

tra*_*vis 7 c# asp.net-mvc html-helper razor asp.net-mvc-5

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

@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)
Run Code Online (Sandbox Code Playgroud)

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

必须有一个更好的方法来做这个,而不是每个表单元素的内联条件只是添加一个属性,对吗?

tra*_*vis 2

感谢Steven Muecke提供的所有帮助(在上面的评论和他的链接 答案中给他所有的赞成票)。这是解决方案

对于具有此属性的模型:

[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; }
Run Code Online (Sandbox Code Playgroud)

创建这个扩展方法:

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 });
}
Run Code Online (Sandbox Code Playgroud)

然后在视图中使用它,如下所示:

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

模型属性的所有元数据将在页面上第一次调用时显示。生成的 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" />
Run Code Online (Sandbox Code Playgroud)