【问题标题】:How can limit to 2 decimals in TextBoxFor in MVC?如何在 MVC 中的 TextBoxFor 中限制为 2 位小数?
【发布时间】:2016-11-18 11:36:20
【问题描述】:

我只希望小数点后两位数。

@Html.TextBoxFor(m => m.Viewers, new { @tabindex = 7 })

需要这样的输出:

56.23

456.20

1.21

这样……

【问题讨论】:

标签: asp.net-mvc html.textboxfor


【解决方案1】:

我会在我的视图中使用编辑器模板。我将定义专门针对给定视图的要求定制的视图模型(在这种情况下,将其限制为 2 位小数):

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

或者您可以简单地使用带有模型的正则表达式,例如

[RegularExpression(@"^\d+.\d{0,2}$")]
public decimal Viewers{ get; set; }

然后在html中:

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

TextBoxFor()也适用于正则表达式

@Html.TextBoxFor(m => m.Viewers, new { @tabindex = 7 })

【讨论】:

    【解决方案2】:

    在视图中

    @Html.TextBoxFor(m => m.Viewers, new { @tabindex = 7 }, new { Value=String.Format("{0:0.##}",Model.Viewers) })
    

    在控制器中你也可以格式化你的 String.Format("{0:0.##}",Object.viewers)

    Object- 表示模型(包含字段查看器),传递给 View

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      我建议你在客户端这样格式化你的小数:

      在你的ViewModel:

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

      在你的视图上使用EditorFor:

       @Html.EditorFor(m => m.Viewers, new { @tabindex = 7 })
      

      当此值发布到您的 Controller 时,只需将其修剪为 2 个数字。

      如果您需要验证,请使用正则表达式:

      [RegularExpression(@"^\d+\.\d{0,2}$")] //this line
      [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
      public decimal Viewers { get; set; }
      

      【讨论】:

        【解决方案4】:

        如果我使用。

        String.Format("{0:0.00}", 123.4567);     
        

        所以结果:

         // "123.46"
        

        所以你可以试试这个

        @Html.TextBoxFor(m => String.Format("{0:0.00}", m.Viewers) , new { @tabindex = 7 })
        

        【讨论】:

        • “HTTP 错误 404.0 - 未找到您要查找的资源已被删除、更改名称或暂时不可用。” - 出现这样的错误。
        • 尝试重建这不是 Html 代码错误,请在此处查看此错误的帮助。 support.microsoft.com/en-us/kb/942041
        【解决方案5】:

          $("#Viewers").change(function (e) {
        
                    var num = parseFloat($(this).val());
                    $(this).val(num.toFixed(2));
        });
           @Html.TextBoxFor(m => m.Viewers, new { @tabindex = 7 })

        谢谢大家回复我!!! :)

        【讨论】:

          猜你喜欢
          • 2016-06-22
          • 1970-01-01
          • 2014-06-06
          • 1970-01-01
          • 2014-07-07
          • 2018-06-27
          • 1970-01-01
          • 2021-10-11
          • 1970-01-01
          相关资源
          最近更新 更多