【问题标题】:Accessing the model attributes in a helper extension class访问辅助扩展类中的模型属性
【发布时间】:2016-05-05 17:28:55
【问题描述】:

如果属性[Editable(false)] 存在于模型中的属性上,则尝试创建禁用的文本框。

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

型号:

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

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

有没有在这里检查模型,如果它被禁用,然后将禁用属性添加到输入元素?

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

这是我编写的一个助手,如果模型属性被标记为必需,它会在标签上添加一个“*”。 ModelMetaData 有一个 IsReadonly 属性,可以利用。您应该能够进行正确的替换以对文本框进行更改。

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);
    }
}

【讨论】:

    猜你喜欢
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    相关资源
    最近更新 更多