【发布时间】:2013-02-05 05:39:08
【问题描述】:
我需要将 4 位小数四舍五入为 2 位并在 MVC 3 UI 中显示
类似这样的 58.8964 到 58.90
尝试遵循此How should I use EditorFor() in MVC for a currency/money type? 但没有工作。
当我使用 TextBoxFor=> 时,我在这里删除了 ApplyFormatInEditMode。甚至 我尝试使用 ApplyFormatInEditMode ,但没有任何效果。仍然显示 我 58.8964。
我的模型类
[DisplayFormat(DataFormatString = "{0:F2}")]
public decimal? TotalAmount { get; set; }
@Html.TextBoxFor(m=>m.TotalAmount)
我怎样才能完成这个回合?
我不能在这里使用 EditorFor(m=>m.TotalAmount),因为我需要传递一些 htmlAttributes
编辑:
用MVC源码调试后,内部使用
string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);
在 InputExtension.cs 的 MvcHtmlString InputHelper() 方法中,以对象值为参数并进行转换。他们在那里没有使用任何显示格式。我们该如何解决?
我设法以这种方式修复。由于我有一个自定义助手,我可以使用以下代码进行管理
if (!string.IsNullOrEmpty(modelMetaData.DisplayFormatString))
{
string formatString = modelMetaData.DisplayFormatString;
string formattedValue = String.Format(CultureInfo.CurrentCulture, formatString, modelMetaData.Model);
string name = ExpressionHelper.GetExpressionText(expression);
string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
return htmlHelper.TextBox(fullName, formattedValue, htmlAttributes);
}
else
{
return htmlHelper.TextBoxFor(expression, htmlAttributes);
}
【问题讨论】:
-
尝试使用
[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)] -
@Karthik,当然。但是让我尝试调试 MVC 源代码,看看它在哪里设置
-
We now allow passing in HTML attributes in EditorFor as an anonymous object来自MVC 5.1 update
标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4