繁体   English   中英

使用继承时的MVC / Razor DisplayAttribute

[英]MVC/Razor DisplayAttribute when using inheritence

我正在设置一堆用于维护参考表的Razor页面。 数据上下文中的基本结构是这样的:

public class RefTableBase {
    public int Id {get;set;}
    public string Value {get;set;}
}

public class UserType: RefTableBase {}

public class ReferenceType: RefTableBase {}

脚手架的Razor页面在那里可以正常工作。 但是,当我有一个调用派生表的类时,页面无法显示我所期望的。

public class SomethingImportant {
    public int Id {get;set;}
    public string Name {get;set;}

    public int UserTypeId {get;set;}
    public virtual UserType UserType {get;set;}

    public int ReferenceTypeId {get;set;}
    public virtual ReferenceType ReferenceType {get;set;}
}

构架index.cshtml页面时,表头看起来像这样:

@model IEnumerable<Models.SomethingImportant>

<table class="table">
    <tr>
        <th>@Html.DisplayNameFor(model => model.Id)</th>
        <th>@Html.DisplayNameFor(model => model.Name)</th>
        <th>@Html.DisplayNameFor(model => model.UserType.Value)</th>
        <th>@Html.DisplayNameFor(model => model.ReferenceType.Value)</th>

但是当页面实际在浏览器中呈现时,列标题显示

Id    Name    Value    Value

当我想要的是:

Id    Name    User Type     Reference Type

我试过在类中的成员上使用DisplayAttribute,但是没有用。

public class SomethingImportant {
    // ...........
    [Display(Name="User Type")]
    public int UserTypeId {get;set;}
    public virtual UserType UserType {get;set;}
    // ...........
}

除了跳过继承并实际为派生类中的每个类设置DisplayAttribute之外,还有什么方法可以使它显示我想要的方式?

您可以简单地将Display属性放在相关属性上:

public class SomethingImportant {
    public int Id {get;set;}
    public string Name {get;set;}

    public int UserTypeId {get;set;}
    [Display(Name="User Type")]//here
    public virtual UserType UserType {get;set;}

    public int ReferenceTypeId {get;set;}
    [Display(Name="Reference Type")]//and here
    public virtual ReferenceType ReferenceType {get;set;}
}

并删除视图上的调用.Value

<th>@Html.DisplayNameFor(model => model.Id)</th>
<th>@Html.DisplayNameFor(model => model.Name)</th>
<th>@Html.DisplayNameFor(model => model.UserType)</th>
<th>@Html.DisplayNameFor(model => model.ReferenceType)</th>

如果需要.Value并且它是该类的属性,则可以将Display属性放在这些属性上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM