重写 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)
当将上面的每个对象传递到剃刀视图中时,我期望得到...
- 1.23
- 9.8
但是 DisplayFormat 似乎没有与属性一起覆盖,而是我得到...
- 1.23
- 9.87
有谁知道如何解决这?
编辑: 抱歉,没说清楚。如果我有 n*派生类
,如何才能以一种不涉及每种类型的新文件的方式解决问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以编写自定义显示模板 (
~/Views/Shared/DisplayTemplates/MyDerivedClass.cshtml
):然后在主
Index.cshtml
视图中:You could write a custom display template (
~/Views/Shared/DisplayTemplates/MyDerivedClass.cshtml
):and then inside your main
Index.cshtml
view: