【问题标题】:MetadataType bug in MVC3?MVC3 中的元数据类型错误?
【发布时间】:2012-03-14 16:02:53
【问题描述】:

我在使用 MetadataType / buddy 类来让 DisplayName / Display 属性在 MVC3 中的 Entity Framework 类上工作时绞尽脑汁。在我看来,如果我使用@Html.LabelFor,我仍然只是获取属性名称而不是显示属性。我的用例和设置非常简单:

[MetadataType(typeof(ProductMetadata))]
public partial class Product
{
}

public class ProductMetadata
{
    [Display(Name = "Why does this not work????")]
    object ProductName { get; set; }

    [Display(Name = "Discontinued Date")]
    object DiscontinuedDate { get; set; }
}

如果我然后使用像 LabelFor 这样的 Html 帮助器:

@Html.LabelFor(m => m.First().ProductName)

我仍然只是在输出中获取属性名称。即使我在自定义 Html 扩展中以编程方式执行此操作,我也只是获取属性名称而不是提取的属性值:

ModelMetadata.FromLambdaExpression(expression, html.ViewData).DisplayName

对此的任何想法或帮助将不胜感激。我在这里有什么遗漏吗?

【问题讨论】:

  • 别说是MVC3的bug。它已经存在很长时间了,以至于有人报告这样的错误 :) 而且这是一个简单的用例,它永远不会通过 QA。
  • 我认为这是我缺少的东西。但是,这是 preview1 中的一个错误,这让我很好奇。有趣的是,无论我查看该代码多少次,我都没有注意到我没有设置属性访问级别。

标签: asp.net-mvc asp.net-mvc-3


【解决方案1】:

它不起作用,因为属性在 ProductMetadata 类中是私有的。改成

public class ProductMetadata
{
    [Display(Name = "It works!!!")]
    public object ProductName { get; set; }

    [Display(Name = "Discontinued Date")]
    public object DiscontinuedDate { get; set; }
}

【讨论】:

    【解决方案2】:

    尝试使用 DisplayNameAttribute

    [DisplayName("Propertyname")]
    public string PropertyName {get;set;}
    

    【讨论】:

    • 我应该再澄清一点。无论我使用 DisplayName 属性还是 Display 属性,我都会得到相同的结果。
    猜你喜欢
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2011-09-30
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多