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

时间:2015-09-08 22:28:24

标签: c# asp.net-mvc razor asp.net-mvc-5 html-helper

我正在构建一个表单,我必须继续使用内联条件来添加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=""的形式呈现给客户端,这足以让浏览器将该字段设为只读。

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

1 个答案:

答案 0 :(得分:2)

感谢Steven Muecke提供的所有帮助(在评论和linked answers中向他提供所有上述选票。这是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" />