5

给定这样的视图模型:

public class ParentViewModel
{
    public object ChildViewModel { get; set; }
}

如果我Html.LabelFor这样使用:

@Html.LabelFor(model => model.ChildViewModel)

我会得到这样的输出:

<label for="Model_ChildViewModel">ChildViewModel</label>

我真正想要的是生成的标签使用DisplayName应用于对象 EG 的属性

[DisplayName("My Custom Label")]
public class ChildViewModel
{
}

输出为:

<label for="Model_ChildViewModel">My Custom Label</label>

我知道该Html.LabelFor方法采用一个需要属性的表达式,它将DisplayName在该属性而不是对象本身上查找属性。

我创建了一个 Html 辅助方法来实现我想要的,如下所示:

public static IHtmlString CreateLabel<TModel>(this HtmlHelper html, Func<TModel, object> func) 
    where TModel : class
    {
        TagBuilder tb = new TagBuilder("label");

        var model = html.ViewData.Model as TModel;
        if (model != null)
        {
            object obj = func(model);
            if (obj != null)
            {
                var attribute = obj.GetType().GetCustomAttributes(
                    typeof(DisplayNameAttribute), true)
                    .FirstOrDefault() as DisplayNameAttribute;

                if (attribute != null)
                {
                    tb.InnerHtml = attribute.DisplayName;
                    return MvcHtmlString.Create(tb.ToString());
                }
                else
                {
                    tb.InnerHtml = obj.ToString();
                    return MvcHtmlString.Create(tb.ToString());
                }
            }
        }

        tb.InnerHtml = html.ViewData.Model.ToString();
        return MvcHtmlString.Create(tb.ToString());
    }

我的助手没有采用表达式,而是采用 aFunc<TModel, object>来返回我要检查DisplayName属性的对象。

我遇到的第一个问题是当我尝试像这样在 razor 中调用此方法时:

@Html.CreateLabel(model => model.ChildObject)

我收到以下错误:

The type arguments for method 'CreateLabel<TModel>(this HtmlHelper,
Func<TModel, object>) cannot be inferred from usage. Try specifying
the arguments explicitly.'

所以我改为这样调用方法:

 @{ Html.CreateLabel<ChildViewModel>(model => model.ChildObject); }

但没有任何东西被渲染。如果我使用调试器单步执行我的辅助方法,则会生成标签标记,但在呈现我的页面时没有显示任何内容。

所以我的问题是:

  • 如何解决此问题以为我的视图生成标签?
  • 我必须做什么才能推断出泛型参数?
  • 有没有办法编写 Html 助手来做同样的事情,但使用表达式?我没有使用表达式的经验,所以不知道从哪里开始。

更新

我想我会发布最终代码,因为我做了一些小改动。首先,我查看了 MVC 源代码中的帮助程序,并决定根据提供的示例将该方法拆分为三个单独的方法。我还删除了所有TagBuilder内容,因为我真正需要的是生成要在<legend></legend>标签之间注入的文本。最终代码如下。再次感谢 Sylon 帮助我解决这个问题。

public static IHtmlString LegendTextFor<TModel, TObject>(this HtmlHelper<TModel> html, Expression<Func<TModel, TObject>> expression)
{
    return LegendTextHelper(html,
        ModelMetadata.FromLambdaExpression(expression, html.ViewData),
        ExpressionHelper.GetExpressionText(expression),
        expression.Compile().Invoke(html.ViewData.Model));
}

private static IHtmlString LegendTextHelper<TModel, TObject>(this HtmlHelper<TModel> html, ModelMetadata metadata, string htmlFieldName, TObject value)
{
    string resolvedLabelText = metadata.DisplayName ?? value.GetDisplayName() ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();

    if (String.IsNullOrEmpty(resolvedLabelText))
        return MvcHtmlString.Empty;

    return MvcHtmlString.Create(resolvedLabelText);
}

private static string GetDisplayName<T>(this T obj)
{
    if (obj != null)
    {
        var attribute = obj.GetType()
            .GetCustomAttributes(typeof(DisplayNameAttribute), false)
            .Cast<DisplayNameAttribute>()
            .FirstOrDefault();

        return attribute != null ? attribute.DisplayName : null;
    }
    else
    {
        return null;
    }
}
4

1 回答 1

2

我刚刚为标签创建了一个自定义 Html 帮助器,它可以满足您的需求:

html助手:

public static class HtmlHelperExtensions
{

    public static MvcHtmlString LabelForCustom<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

        string customDisplayName = null;

       var value = expression.Compile().Invoke(html.ViewData.Model);

       if (value != null)
       {
          var attribute = value.GetType().GetCustomAttributes(typeof(DisplayNameAttribute), false)
           .Cast<DisplayNameAttribute>()
           .FirstOrDefault();

           customDisplayName = attribute != null ? attribute.DisplayName : null;
       }

         string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
        string labelText = metadata.DisplayName ?? customDisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
        if (String.IsNullOrEmpty(labelText))
        {
            return MvcHtmlString.Empty;
        }

        TagBuilder tag = new TagBuilder("label");
         tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
        tag.SetInnerText(labelText);
        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }
}

我的示例模型:

public class Parent
{
    public object Child { get; set; }
}

[DisplayName("yo")]
public class Child 
{
   public int Id { get; set; }
}

看法:

@Html.LabelForCustom(m => m.Child)  @*prints yo*@
于 2013-04-12T11:06:42.087 回答