asp.net-mvc 在视图中格式化小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9721673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format a decimal in a view
提问by Mark
If I have a decimal value in a field, and I am trying to display on a page, how do I format it (I would use string.format in web forms):
如果我在一个字段中有一个十进制值,并且我试图在页面上显示,我该如何格式化它(我会在 web 表单中使用 string.format):
@Html.DisplayFor(Function(modelItem) String.Format("{0:n0}",currentItem.QualityM1))
That errors in VS2010 with the messae: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
VS2010 中的错误信息:模板只能用于字段访问、属性访问、单维数组索引或单参数自定义索引器表达式。
回答by tugberk
I wouldn't do this inside the view. It would be better to centralize this and provide this information as metadata as below:
我不会在视图中这样做。最好将其集中起来并将此信息作为元数据提供,如下所示:
public class Foo {
[DisplayFormat(DataFormatString = "{0:n0}")]
public decimal Bar { get; set; }
}
Then use this as usual:
然后像往常一样使用它:
@Html.DisplayFor(m => m.Bar)
回答by Richard Dalton
Do you need to use Html.DisplayFor?
你需要使用 Html.DisplayFor 吗?
Otherwise you can just do:
否则你可以这样做:
@String.Format("{0:n0}",currentItem.QualityM1)
回答by user3302942
dont do in DisplayFor... in the class set the atributte like this one.
不要在DisplayFor......在课堂上设置这样的属性。
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N2}")]
public virtual decimal Valor
{
get;
set;
}

