【问题标题】:Howto configure complex types in ASP.NET MVC (4) with MvcExtensions如何在ASP.NET MVC中配置复杂类型(四)用Mvc Extensions
【发布时间】:2012-09-07 11:02:44
【问题描述】:

我有一个具有一些复杂属性的模型:

public class TestModel
{
    public string Prop1 { get; set; }
    public SubClass Prop2 { get; set; }
}
public class SubClass 
{
    public string Test { get; set; }
}

public class TestModelMetadata : ModelMetadataConfiguration<TestModel>
{
    public TestModelMetadata ()
    {
        Configure(m => m.Prop1).DisplayName("is going to be displayed");
        Configure(m => m.Prop2.Test).DisplayName("is NOT going to be displayed");
    }
}

当我试图在视图上显示模型时:

@Html.LabelFor(m => m.Prop1)
@Html.LabelFor(m => m.Prop2.Test)

显示 Prop1 的正确标签,而 Prop2.Test 则不显示。

有人知道解决方案吗?谢谢!!!!!!

【问题讨论】:

  • 感谢@Pluc。刚刚更新了问题,使其也包含视图。

标签: asp.net asp.net-mvc asp.net-mvc-4 mvcextensions


【解决方案1】:

据我所知,应为每种类型创建元数据配置,在您的情况下为 SubClass :

public class SubClassMetadata : ModelMetadataConfiguration<SubClass>
{
    public SubClassMetadata()
    {
        Configure(m => m.Test).DisplayName("is going to be displayed1");
    }
}

此外,如果您想使用 @Html.DisplayForModel 显示具有子类属性的模型,您应该覆盖对象的显示模板,因为默认 mvc(3 - 我不知道它是否在 v4 中更改)显示模板的对象跳过“ComplexType “ 特性。自定义默认模板的起点可以是https://github.com/ASP-NET-MVC/ASP.NET-Mvc-3/blob/master/mvc3/src/MvcFuturesFiles/DefaultTemplates/DisplayTemplates/Object.ascx

希望对你有帮助。

【讨论】:

  • 谢谢,就是这样。不幸的是,我更愿意以我认为正确的方式配置它 (Configure(m =&gt; m.Prop2.Test).DisplayName("is ...");) - 因为在那里,我可以灵活地配置我的 SubClass,具体取决于我使用的型号。
  • 关于@Html.DisplayFor:这对我来说是错误的。我的意思是:LabelFor
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
  • 2012-09-16
  • 2011-12-22
  • 1970-01-01
相关资源
最近更新 更多