如何避免在定义Html.EditorFor()的htmlattribute时使用重复的内联条件?

本文关键字:条件 htmlattribute 定义 何避免 Html EditorFor | 更新日期: 2023-09-27 18:11:42

我正在构建一个表单,我必须保持使用内联条件来添加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="",这足以让浏览器使该字段只读。

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

如何避免在定义Html.EditorFor()的htmlattribute时使用重复的内联条件?

感谢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; }

创建这个扩展方法:

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" />