开发者

Overriding DisplayFormat(DataFormatString)

public abstract class MyBaseClass
{
    [DisplayFormat(DataFormatString = "{0:0.00}")]
    public virtual decimal Value
    开发者_开发技巧{
        get { return 1.23456m; }
    }
}

public class MyDerivedClassA : MyBaseClass
{
    [DisplayFormat(DataFormatString = "{0:0.0}")]
    public override decimal Value
    {
        get { return 9.87654m; }
    }
}

...

public class MyDerivedClassZ : MyBaseClass
{
    [DisplayFormat(DataFormatString = "{0:0.000}")]
    public override decimal Value
    {
        get { return 7.654321m; }
    }
}

-

@model MyBaseClass

@Html.DisplayFor(m => @Model.Value)

When passing each of the to object above into the razor view I expected to get...

  • 1.23
  • 9.8

However the DisplayFormat does not seem to override along with the property, instead I get...

  • 1.23
  • 9.87

Does anyone know how to get around this?

EDIT: Sorry, wasn't clear. If I have n*Derived Classes how can I solve the problem in a way that won't involve a new file for each and every type?


You could write a custom display template (~/Views/Shared/DisplayTemplates/MyDerivedClass.cshtml):

@model MyDerivedClass           
@Html.DisplayFor(x => x.Value)

and then inside your main Index.cshtml view:

@model MyBaseClass
@Html.DisplayForModel()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜