我试图格式化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) })
有我的代码,我在做的,这里是该字段的网站本身包含在editor-field div当然。
<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">
任何帮助,将不胜感激,谢谢!
解决方法
您可以使用[DisplayFormat]属性来装饰您的GoalAmount视图模型属性:
[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)