【问题标题】:How to Format nullable decimal as currency in mvc 3 razor view for display purpose only如何在 mvc 3 razor 视图中将可空小数格式化为货币仅用于显示目的
【发布时间】:2013-03-05 22:01:02
【问题描述】:

我需要帮助在 mvc 应用程序的 razor 视图中将可为空的十进制字段格式化为货币(带有美元符号和逗号)。下面是我的模态和视图代码。

型号

[Display(Name = "Eligible Amount")]
[RequiredIfProjectEngineerSelected("ProjectEngineerId", "", ErrorMessage = "Eligible Amount field is Required")]        
[DisplayFormat(DataFormatString = "{0:c}")]        
public decimal? EligibleAmount { get; set; }

查看

@{var formated = String.Format("{0:c}",  decimal)decimal.Parse(@Model.project.ProjectTotalCost.HasValue ? @Model.project.ProjectTotalCost.Value.ToString() : ""));}
@Html.TextBoxFor(model => model.project.ProjectTotalCost, new { @Value = formatted})

它在 TextBoxFor 控件中显示格式化的货币值。但我在这里面临的问题是,当我尝试更新值时,出现验证错误,提示“值与格式不匹配”​​。

【问题讨论】:

  • 如果说显示格式,需要@model.EligibleAmount .ToString("c")

标签: asp.net asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

首先,您应该将视图中显示的两行代码替换为一行代码:

@Html.EditorFor(x => x.EligibleAmount)

这将考虑到您在模型上定义的DisplayFormat 属性,您无需在视图中重复此格式。您只需将ApplyFormatInEditMode 属性设置为true 即可在编辑模式下启用它:

[Display(Name = "Eligible Amount")]
[RequiredIfProjectEngineerSelected("ProjectEngineerId", "", ErrorMessage = "Eligible Amount field is Required")]        
[DisplayFormat(DataFormatString = "{0:c}", ApplyFormatInEditMode = true)]        
public decimal? EligibleAmount { get; set; }

好的,这解决了显示部分。但是模型绑定部分仍然是一个问题。为此,您可以编写一个自定义模型绑定器,该绑定器将考虑您的 DisplayFormat 属性中定义的格式。我已经在this post 展示了一个带有日期时间的模型绑定器的示例。您所要做的就是调整它以适应decimal 时间,这应该是一项微不足道的任务。

【讨论】:

  • 感谢 Drain 帮助我。我无法将控件从 TextBoxFor 更改为 EditorFor,因为我需要应用样式。
  • @Darin decimalNullable<decimal> 的工作方式不会不同吗?
【解决方案2】:

感谢您在这方面给我的所有建议。我可以通过使用 ModelBinder 来解决这个问题。

根据Darin's answer,我无法将控件从 TextBoxFor 更改为 EditorFor,因为我需要对其应用样式。 ModelBinder 也适用于 TextBoxFor 控件。

~巴拉吉

【讨论】:

  • 我遇到了同样的问题。你还有这个的代码吗?谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
  • 2012-05-31
  • 1970-01-01
  • 2011-09-18
  • 1970-01-01
  • 2020-07-18
相关资源
最近更新 更多