gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:36:16 26 4
gpt4 key购买 nike

我正在构建一个表单,我必须继续使用内联条件来添加 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感谢所有帮助(在评论和他的 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 });
}

然后像这样在 View 中使用它:

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

关于c# - 如何避免重复内联条件来定义 Html.EditorFor() 的 htmlAttributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32468253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com