我正在尝试格式化Html.EditorFor文本框以进行货币格式化,我试图将其基于此线程String.Format for currency on a TextBoxFor。但是,我的文字仍显示为0.00,没有货币格式。
<div class="editor-field">
@Html.EditorFor(model => model.Project.GoalAmount, new { @class = "editor- field", Value = String.Format("{0:C}", Model.Project.GoalAmount) })
我正在做的是代码,这里是编辑器字段div中包含的网站中该字段的html。
<input class="text-box single-line valid" data-val="true"
data-val-number="The field Goal Amount must be a number."
data-val-required="The Goal Amount field is required."
id="Project_GoalAmount" name="Project.GoalAmount" type="text" value="0.00">
任何帮助将不胜感激,谢谢!
答案 0 :(得分:69)
您可以使用GoalAmount
属性装饰[DisplayFormat]
视图模型属性:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public decimal GoalAmount { get; set; }
在视图中简单地说:
@Html.EditorFor(model => model.Project.GoalAmount)
EditorFor帮助器的第二个参数完全不符合您的想法。它允许您将其他ViewData传递给编辑器模板,它不是htmlAttributes。
另一种可能性是为货币(~/Views/Shared/EditorTemplates/Currency.cshtml
)编写自定义编辑器模板:
@Html.TextBox(
"",
string.Format("{0:c}", ViewData.Model),
new { @class = "text-box single-line" }
)
然后:
@Html.EditorFor(model => model.Project.GoalAmount, "Currency")
或使用[UIHint]
:
[UIHint("Currency")]
public decimal GoalAmount { get; set; }
然后:
@Html.EditorFor(model => model.Project.GoalAmount)