2015-09-08 41 views
7

我建立一个形式的htmlAttributes和我有使用条件的内联添加readonly HTML属性保持:如何避免重复内嵌条件语句来定义Html.EditorFor()

@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=""的形式呈现给客户端,并且这足以让浏览器将该字段设置为只读。

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

+3

你可以创建你自己的HtmlHelper扩展方法 - 说'@ Html.ReadOnlyEditorFor(表达,htmlAttributes,isReadonly =真)'其中属性取决于的增值'isReadonly'参数 –

+0

@StephenMuecke如何修改该助手内的htmlAttributes对象以添加/删除'@ readonly'属性? – travis

+1

参考[这个答案](http://stackoverflow.com/questions/30127866/create-checkboxfor-mvc-helper-with-title-attribute-from-model-description/30135407#30135407)为例 –

回答

2

感谢Steven Muecke所有的帮助(给他所有的意见上面的评论和他的linkedanswers)。这里是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) 

而且所有的该模型的属性元数据将显示为第一个 ins以确保它在页面上被调用。生成的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" />