Oto jak to zrobić:
Model:
[ReadOnly(true)]
public string Email { get { return DbUser.Email; } }
Widok:
@Html.TheEditorFor(x => x.Email)
Rozszerzenie:
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));
}
}
}
Oczywiście mój wydawca robi banda więcej rzeczy, jak dodawanie etykietę, dodając wymaganą klasę do tej etykiety stosownie do potrzeb, dodając DisplayFor
jeżeli nieruchomość jest ReadOnly
EditorFor
Jeśli nie, dodanie ValidateMessageFor
i ostatecznie owijanie tego w Div
, które może być przypisane Html Attributes
... moim Views
są super czyste.
Jeśli jest tylko do odczytu, to nie jest już redaktorem. Najprawdopodobniej przez DisplayFor –
Tworzenie edytora tylko raz pokonuje jego obiekt. Dlaczego nie skorzystać z DisplayFor? – ChrisBint
możliwy duplikat [jak ustawić wyłączony atrybut w html textbox w asp.net-mvc?] (Http://stackoverflow.com/questions/3443460/how-do-i-set-disabled-attribute-on-html -textbox-in-asp-net-mvc) –