asp.net-mvc MVC 中 TextBoxFor 的 DisplayFormat
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14700873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DisplayFormat for TextBoxFor in MVC
提问by Murali Murugesan
I need to round off 4 digit decimal to 2 digits and show in MVC 3 UI
我需要将 4 位小数四舍五入为 2 位并在 MVC 3 UI 中显示
Something like this 58.8964 to 58.90
像这样的 58.8964 到 58.90
Tried following this How should I use EditorFor() in MVC for a currency/money type?but not working.
尝试遵循此我应该如何在 MVC 中使用 EditorFor() 来处理货币/货币类型?但不工作。
As i am using TextBoxFor=> i removed ApplyFormatInEditMode here. Even i tried with ApplyFormatInEditMode , but nothing works. Still showing me 58.8964.
当我使用 TextBoxFor=> 时,我在这里删除了 ApplyFormatInEditMode。即使我尝试过 ApplyFormatInEditMode ,但没有任何效果。仍然显示给我 58.8964。
MyModelClass
我的模型类
[DisplayFormat(DataFormatString = "{0:F2}")]
public decimal? TotalAmount { get; set; }
@Html.TextBoxFor(m=>m.TotalAmount)
How can i achieve this round off?
我怎样才能实现这一轮?
I can't use EditorFor(m=>m.TotalAmount) here, as i need to pass some htmlAttributes
我不能在这里使用 EditorFor(m=>m.TotalAmount),因为我需要传递一些 htmlAttributes
Edit:
编辑:
After debugging with MVC source code, they internally use
用MVC源码调试后,内部使用
string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);
in MvcHtmlString InputHelper() method of InputExtension.cs that takes object valueas parameter and converting. They are not using any display format there. How could we fix?
在 InputExtension.cs 的 MvcHtmlString InputHelper() 方法中,将 对象值作为参数并进行转换。他们没有在那里使用任何显示格式。我们怎么修?
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);
}
采纳答案by Darin Dimitrov
You should use Html.EditorForinstead of Html.TextBoxForif you want the custom format to be taken into account:
如果要考虑自定义格式,则应使用Html.EditorFor而不是Html.TextBoxFor:
@Html.EditorFor(m => m.TotalAmount)
Also make sure that you have set ApplyFormatInEditModeto true:
还要确保您已设置ApplyFormatInEditMode为 true:
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal? TotalAmount { get; set; }
The DisplayFormat attribute is intended to be used only with templated helpers such as EditorForand DisplayFor. This is the recommended approach instead of using TextBoxFor.
DisplayFormat 属性旨在仅与模板化助手(例如EditorFor和 )一起使用DisplayFor。这是推荐的方法,而不是使用TextBoxFor.
回答by Sam Sippe
This works in MVC5
这适用于 MVC5
@Html.TextBoxFor(m => m.TotalAmount, "{0:0.00}")
回答by Karthik Chintala
Try like this:
像这样尝试:
@{
var format = String.Format("{0:0.00}", Model.TotalAmount);
}
@Html.TextBoxFor(m => m.TotalAmount, format)
Hope it helps.
希望能帮助到你。
回答by lko
If you need more control of the field being displayed (vs. a built in EditorFor template) create a custom EditorFor template yourself. Inside an EditorFor template, the built in Html Helpers like @Html.TextBox()can be used with automatic client side validation and Display attributeswhich are usually only available to EditorForand DisplayFor.
如果您需要对显示的字段进行更多控制(相对于内置 EditorFor 模板),请自行创建自定义 EditorFor 模板。在 EditorFor 模板中,内置的 Html Helpers@Html.TextBox()可以与自动客户端验证和 Display 属性一起使用,这些属性通常只对EditorFor和可用DisplayFor。
For example looping through a List of items. The input name has to have an unbroken index.
例如循环遍历项目列表。输入名称必须有一个完整的索引。
// Optional, if you require a custom input name for binding
String fieldName = String.Format("FieldNameForBinding[{0}].Property", index)
@Html.EditorFor(m => m.Property, "MyCustomEditorTemplate", fieldName)
Then you can setup your model
然后你可以设置你的模型
[CustomValidation(..optional..)]
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal? TotalAmount { get; set; }
The EditorFor template (in e.g. ~/Views/Shared/EditorFor/MyCustomEditorTemplate.cshtml)
Note the name is left empty, it comes from the fieldNameautomatically. You can see it in the ViewData.TemplateInfo.HtmlFieldPrefix. Now you have complete control over the display of the field.
EditorFor 模板(例如 ~/Views/Shared/EditorFor/MyCustomEditorTemplate.cshtml) 注意名称留空,它来自 fieldName自动。你可以在ViewData.TemplateInfo.HtmlFieldPrefix. 现在您可以完全控制字段的显示。
@model object
@{
Decimal? actualValue = (Decimal?)Model;
}
// The TextBox and ValidationMessage "names" are empty, they are filled
// from the htmlFieldName given via the @Html.EditorFor() call.
@Html.TextBox("", actualValue, new { @class = "cssClass" })
@Html.ValidationMessage("")
The idea is that you can customize the input field however you would like, and use e.g. @Html.TextBox() which outsideof a custom EditorFor template would not utilize the built in client-side validation. You don't need to use the custom naming of the input field, that was simply an example of the usefulness of this solution. You can customize the way the data is presented (CSS, etc.) instead of relying on the built in EditorFor templates.
这个想法是,您可以根据需要自定义输入字段,并使用例如 @Html.TextBox(),它在自定义 EditorFor 模板之外不会使用内置的客户端验证。您不需要使用输入字段的自定义命名,这只是此解决方案有用性的一个示例。您可以自定义数据的呈现方式(CSS 等),而不是依赖于内置的 EditorFor 模板。
回答by Yury Dzhantuganov
I solve that issue in this way:
我是这样解决这个问题的:
@Html.TextBoxFor(model => model.dtArrivalDate, ModelMetadata.FromLambdaExpression(model => model.dtArrivalDate, ViewData).EditFormatString)
or create next extension:
或创建下一个扩展:
public static class HtmlExtensions
{
public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return htmlHelper.TextBoxFor(expression, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).EditFormatString, htmlAttributes);
}
}
But you need to set ApplyFormatInEditMode=truein DisplayFormatAttributeon your field.
但你需要设置ApplyFormatInEditMode=true在DisplayFormatAttribute你的领域。

