Accessing the model attributes in a helper extensi

2019-01-29 11:42发布

问题:

Trying to create a disabled textbox if the attribute [Editable(false)] is present on a property in the model.

public static IHtmlString SmartTextBox(this HtmlHelper helper, string content)
{
     string htmlString = String.Format("<input type="text">{0}</input>", content);
     return new HtmlString(htmlString);
}

Model:

public class User
{        
    public int Age { get; set; }

    [Editable(false)]
    public string Name { get; set; }
}

Is there anyway to check the model here and then add the disabled attribute to the input element if it's been disabled?

回答1:

Here's a helper I wrote that adds an '*' to a label if the model property is marked as required. ModelMetaData has an IsReadonly property to might be able to leverage. You should be able to make the correct substitutions to make the changes for a textbox.

public static class LabelExtensions
{
    public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html,
        Expression<Func<TModel, TValue>> expression, IDictionary<String, Object> htmlAttributes,
        String requiredMarker = "*")
    {
        return LabelHelper(html, ModelMetadata.FromLambdaExpression(expression, html.ViewData),
            ExpressionHelper.GetExpressionText(expression), null, htmlAttributes, requiredMarker);
    }

    public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html,
        Expression<Func<TModel, TValue>> expression, Object htmlAttributes, String requiredMarker)
    {
        return LabelFor(html, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), requiredMarker);
    }

    internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, String htmlFieldName,
        String labelText = null, IDictionary<String, Object> htmlAttributes = null, String requiredMarker = null)
    {
        var resolvedLabelText = labelText ??
                                metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();

        var tag = new TagBuilder("label");
        tag.Attributes.Add("for",
            TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
        tag.SetInnerText(resolvedLabelText);
        tag.MergeAttributes(htmlAttributes, true);

        if (metadata.IsRequired && !String.IsNullOrWhiteSpace(requiredMarker))
        {
            var requiredSpan = new TagBuilder("span") {InnerHtml = requiredMarker};
            requiredSpan.AddCssClass("required");

            tag.InnerHtml += requiredSpan;
        }

        var result = tag.ToString(TagRenderMode.Normal);

        return new MvcHtmlString(result);
    }
}