我需要帮助在mvc应用程序的剃刀视图中将可以为空的十进制字段格式化为货币(带有美元符号和逗号)。下面是我的模态和视图代码。
模型:
[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控件中显示格式化的货币值。但是我在这里遇到的问题是,当我尝试更新值时,得到验证错误,说“值不匹配格式”。
答案 0 :(得分:5)
首先,您应该用一行代码替换您在视图中显示的2行代码:
@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
展示了一个带有DateTime的模型绑定器的示例。您所要做的就是将其调整为decimal
时间,这应该是一项微不足道的任务。
答案 1 :(得分:0)
感谢您就此提出的所有建议。我可以使用ModelBinder解决这个问题。
作为Per Darin's answer,我无法将控件从TextBoxFor更改为EditorFor,因为我需要在其上应用样式。 ModelBinder也可以与TextBoxFor控件一起使用。
〜巴拉吉