Skip to content

Instantly share code, notes, and snippets.

@dieseltravis
Last active September 9, 2015 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dieseltravis/99c31d22766b75f52a9e to your computer and use it in GitHub Desktop.
Save dieseltravis/99c31d22766b75f52a9e to your computer and use it in GitHub Desktop.
asp.net mvc html extension for adding an attribute to an editor
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 });
}
[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; }
<div class="row">
<div class="col-xs-3">
<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" />
</div>
</div>
<div class="row">
<div class="col-xs-3">
<input class="form-control input-lg text-box single-line" id="EventDate" name="EventDate" type="date" value="08-01-2015" />
</div>
</div>
<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>
<div class="row">
<div class="col-xs-3">
@Html.ReadOnlyEditorFor(model => model.EventDate, new { @class = "form-control input-lg", @type = "date" }, Model.IsEditorReadOnly)
</div>
</div>
@dieseltravis
Copy link
Author

The solution is to not call it twice in the razor since it will only work correctly the first time. ¯_(ツ)_/¯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment