asp.net-mvc DisplayFormat 未应用于十进制值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7843099/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:31:54  来源:igfitidea点击:

DisplayFormat not getting applied on decimal value

asp.net-mvcasp.net-mvc-3decimalmvc-editor-templatesdisplayformat

提问by Jerad Rose

I have a model property I'm trying to render using an EditorFor template, and I'm trying to apply formatting using the DisplayFormat attribute. However, it's not working at all -- it's totally being ignored.

我有一个模型属性,我正在尝试使用 EditorFor 模板呈现,并且我正在尝试使用 DisplayFormat 属性应用格式。然而,它根本不起作用——它完全被忽略了。

Here is my template:

这是我的模板:

@model System.Decimal?
@Html.TextBoxFor(m => m)

Here is my model:

这是我的模型:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0.00}")]
public decimal? Retail { get; set; }

Here is my view:

这是我的观点:

@Html.EditorFor(m => m.Retail)

But it's rendering a textbox with the following value:

但它渲染了一个具有以下值的文本框:

189.9900

189.9900

It seems pretty straight forward, but it's not working, and I have no idea why.

这看起来很简单,但它不起作用,我不知道为什么。

UPDATE:Just for kicks, I tried it with a DisplayFor template, and it worked:

更新:只是为了踢球,我用 DisplayFor 模板试了一下,它有效:

@Html.DisplayFor(m => m.Retail)

So why would the DisplayFor template work, but not the EditorFor template, when I've set ApplyFormatInEditModeto true?

那么当我设置ApplyFormatInEditMode为 true时,为什么 DisplayFor 模板可以工作,而 EditorFor 模板不行?

UPDATE 2:Never mind, the reason that worked is because my Decimal display template was hard-coded to format that way. So my display template also does not work.

更新 2:没关系,有效的原因是因为我的十进制显示模板是硬编码的。所以我的显示模板也不起作用。

采纳答案by Jerad Rose

Darin Dimitrov posted this answer, and I was able to get it working using his solution:

Darin Dimitrov 发布了这个答案,我能够使用他的解决方案让它工作:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue)

A bit crude, IMO, that this doesn't work w/ TextBoxFor, but at least it works.

有点粗糙,IMO,这对 w/ 不起作用TextBoxFor,但至少它有效。

回答by Jon

DisplayFormatwon't work like that; if you manually create a text box for the property it doesn't come into play. It would only work if you did

DisplayFormat不会那样工作;如果您手动为该属性创建一个文本框,它就不会起作用。只有当你这样做时它才会起作用

@model System.Decimal?
@Html.DisplayFor(m => m)

回答by wnascimento

Try with this format, it outputs 18.999,00

试试这种格式,它输出 18.999,00

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N}")]