MVC 中 TextBoxFor 的 DisplayFormat [英] DisplayFormat for TextBoxFor in MVC
问题描述
我需要将 4 位小数四舍五入为 2 位并显示在 MVC 3 UI 中
I need to round off 4 digit decimal to 2 digits and show in MVC 3 UI
类似这样的 58.8964 到 58.90
尝试遵循此应该如何我在 MVC 中将 EditorFor() 用于货币/货币类型? 但不起作用.
Tried following this How should I use EditorFor() in MVC for a currency/money type? but not working.
因为我正在使用 TextBoxFor=> 我在这里删除了 ApplyFormatInEditMode.甚至我尝试使用 ApplyFormatInEditMode ,但没有任何效果.仍在显示我 58.8964.
As i am using TextBoxFor=> i removed ApplyFormatInEditMode here. Even i tried with ApplyFormatInEditMode , but nothing works. Still showing me 58.8964.
我的模型类
[DisplayFormat(DataFormatString = "{0:F2}")]
public decimal? TotalAmount { get; set; }
@Html.TextBoxFor(m=>m.TotalAmount)
我怎样才能完成这个回合?
我不能在这里使用 EditorFor(m=>m.TotalAmount),因为我需要传递一些 htmlAttributes
用MVC源码调试后,内部使用
After debugging with MVC source code, they internally use
string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);
在InputExtension.cs的MvcHtmlString InputHelper()方法中,以对象值为参数进行转换.他们没有在那里使用任何显示格式.我们该如何解决?
in MvcHtmlString InputHelper() method of InputExtension.cs that takes object value as parameter and converting. They are not using any display format there. How could we fix?
我设法以这种方式修复.由于我有一个自定义助手,我可以使用以下代码进行管理
I managed to fix in this way. As i have a custom helper, i can able to manage with the below code
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);
}
推荐答案
如果你想要自定义格式,你应该使用 Html.EditorFor
而不是 Html.TextBoxFor
考虑到:
You should use Html.EditorFor
instead of Html.TextBoxFor
if you want the custom format to be taken into account:
@Html.EditorFor(m => m.TotalAmount)
还要确保您已将 ApplyFormatInEditMode
设置为 true:
Also make sure that you have set ApplyFormatInEditMode
to true:
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal? TotalAmount { get; set; }
DisplayFormat 属性仅用于模板化帮助程序,例如 EditorFor
和 DisplayFor
.这是推荐的方法,而不是使用 TextBoxFor
.
The DisplayFormat attribute is intended to be used only with templated helpers such as EditorFor
and DisplayFor
. This is the recommended approach instead of using TextBoxFor
.
这篇关于MVC 中 TextBoxFor 的 DisplayFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!