【问题标题】:DisplayFormat for TextBoxFor in MVCMVC 中 TextBoxFor 的显示格式
【发布时间】: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


【解决方案1】:

这适用于 MVC5

@Html.TextBoxFor(m => m.TotalAmount, "{0:0.00}")

【讨论】:

  • 太好了,如果您想避免使用小数点和符号,请使用此格式化程序“{0:N0}”。
【解决方案2】:

如果您想考虑自定义格式,您应该使用Html.EditorFor 而不是Html.TextBoxFor

@Html.EditorFor(m => m.TotalAmount)

还要确保您已将 ApplyFormatInEditMode 设置为 true:

[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal? TotalAmount { get; set; }

DisplayFormat 属性仅用于模板化帮助程序,例如EditorForDisplayFor。这是推荐的方法,而不是使用TextBoxFor

【讨论】:

  • 但是我需要传递html属性。
  • 为什么 MVC 团队可以将此视为下一个版本的修复和实施?
  • MVC 团队为什么会考虑这样的事情?我不认为这是一个错误。无论如何,您应该使用模板化助手。就我个人而言,我总是使用Html.EditorFor 而从不使用Html.TextBoxFor
  • 是的,正确。但是 EditorFor 不接受 htmlAttributes 作为参数。 :(
  • @DarinDimitrov,好消息,We now allow passing in HTML attributes in EditorFor as an anonymous object 来自MVC 5.1 update
【解决方案3】:

试试这样:

@{
     var format = String.Format("{0:0.00}", Model.TotalAmount);
}
@Html.TextBoxFor(m => m.TotalAmount, format)

希望对你有帮助。

【讨论】:

  • 它不工作。您还将格式化的值传递给 htmlAttributes 参数
  • 我在约会时使用了这种方法。我不能使用 EditorFor,因为它不允许你指定类。
【解决方案4】:

如果您需要对正在显示的字段进行更多控制(相对于内置的 EditorFor 模板),请自行创建自定义 EditorFor 模板。在 EditorFor 模板中,像 @Html.TextBox() 这样的内置 Html Helpers 可以与 自动客户端验证和显示属性一起使用,这些属性通常仅适用于 EditorForDisplayFor

例如循环遍历项目列表。输入名称必须有一个完整的索引。

// 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)

然后你就可以设置你的模型了

[CustomValidation(..optional..)]
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal? TotalAmount { get; set; }

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("")

这个想法是您可以根据需要自定义输入字段,并使用例如@Html.TextBox() 在自定义 EditorFor 模板之外 不会使用内置的客户端验证。您不需要使用输入字段的自定义命名,这只是该解决方案有用性的一个示例。您可以自定义数据的呈现方式(CSS 等),而不是依赖于内置的 EditorFor 模板。

【讨论】:

    【解决方案5】:

    我是这样解决这个问题的:

    @Html.TextBoxFor(model => model.dtArrivalDate, ModelMetadata.FromLambdaExpression(model => model.dtArrivalDate, ViewData).EditFormatString)
    

    或创建下一个扩展:

    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);
        }
    }
    

    但是你需要在你的字段上设置ApplyFormatInEditMode=true in DisplayFormatAttribute

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      • 2012-03-01
      相关资源
      最近更新 更多