Ecco come lo faccio:
Modello:
[ReadOnly(true)]
public string Email { get { return DbUser.Email; } }
Vista:
@Html.TheEditorFor(x => x.Email)
Estensione:
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));
}
}
}
Naturalmente il mio editore sta facendo una più roba gruppo, come l'aggiunta di un'etichetta, l'aggiunta di una classe richiesta a tale etichetta, se necessario, l'aggiunta di un DisplayFor
se la proprietà è ReadOnly
EditorFor
se non lo è, aggiungendo un ValidateMessageFor
e infine avvolgendo tutto ciò in un Div
che può essere assegnato a Html Attributes
ad esso ... il mio Views
è super pulito.
fonte
2013-11-04 23:45:08
Se è una sola lettura, allora non è più un editor. Dovrebbe probabilmente da DisplayFor –
Fare un editor di tipo readonly sconfigge l'oggetto di esso. Perché non usare solo DisplayFor? – ChrisBint
possibile duplicato di [come posso impostare l'attributo disabilitato su textbox html in asp.net-mvc?] (Http://stackoverflow.com/questions/3443460/how-do-i-set-disabled-attribute-on-html -textbox-in-asp-net-mvc) –