Here is how I do it:
Model:
[ReadOnly(true)] public string Email { get { return DbUser.Email; } }
View:
@Html.TheEditorFor(x => x.Email)
Expansion:
namespace System.Web.Mvc { public static class CustomExtensions { public static MvcHtmlString TheEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null) { return iEREditorForInternal(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } private static MvcHtmlString iEREditorForInternal<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) { if (htmlAttributes == null) htmlAttributes = new Dictionary<string, object>(); TagBuilder builder = new TagBuilder("div"); builder.MergeAttributes(htmlAttributes); var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); string labelHtml = labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString(); if (metadata.IsRequired) labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression, new { @class = "required" }).ToHtmlString(); string editorHtml = Html.EditorExtensions.EditorFor(htmlHelper, expression).ToHtmlString(); if (metadata.IsReadOnly) editorHtml = Html.DisplayExtensions.DisplayFor(htmlHelper, expression).ToHtmlString(); string validationHtml = Html.ValidationExtensions.ValidationMessageFor(htmlHelper, expression).ToHtmlString(); builder.InnerHtml = labelHtml + editorHtml + validationHtml; return new MvcHtmlString(builder.ToString(TagRenderMode.Normal)); } } }
Of course, my editor does a bunch more things, for example adding a shortcut, adding the necessary class to this shortcut as necessary, adding DisplayFor , if the ReadOnly EditorFor property, if not, adding ValidateMessageFor and finally assuring it all of a Div that may have Html Attributes assigned to him ... my Views are super clean.
Serj Sagan Nov 04 '13 at 23:45 2013-11-04 23:45
source share