[英]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提供的所有幫助(在評論和他的鏈接 答案中給予他所有上述選票)。 這是解決方案 。
對於具有此屬性的模型:
[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" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.