【问题标题】:String Formatting in C# for Strongly typed viewC# 中用于强类型视图的字符串格式
【发布时间】:2011-07-18 15:02:15
【问题描述】:

我想知道如何将强类型视图价格字段转换为 2 位说明符,就像我的数据库中有一个货币字段,例如将 15 转换为 15.0000,我想在视图中显示 15.00,下面是代码:

<%: Html.TextBoxFor(model =>model.Price, new { maxlength = "5", style = "width:40px;" })%>

我尝试了类似但没有成功的方法:

<%: Html.TextBoxFor(model => String.Format("{0:n}"model.Price), new { maxlength = "5", style = "width:40px;" })%>

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-2 string-formatting strongly-typed-view


【解决方案1】:

您可以在模型上放置一个属性,例如:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:n}")]

如果您不想这样做,则需要使用“旧”样式的文本框:

<%= Html.TextBox("Price", string.Format("{0:n}", Model.Price)) %>

【讨论】:

  • 如果我使用它,那么我无法更新,因为强类型视图会自动更新
【解决方案2】:

试试这个:

<%: Html.TextBoxFor(model => model.Price.ToString("0.00"), new { maxlength = "5", style = "width:40px;" })%>

更新:

您还错过了原始语法中的逗号,这可能也是阻止它以这种方式工作的全部原因。应该是:

<%: Html.TextBoxFor(model => String.Format("{0:n}", model.Price), new { maxlength = "5", style = "width:40px;" })%>

另外,对于 2 位小数,试试这样:

<%: Html.TextBoxFor(model => String.Format("{0:0.00}", model.Price), new { maxlength = "5", style = "width:40px;" })%>

【讨论】:

  • 错误:方法 'ToString' 没有重载需要 1 个参数
  • @Mr A,我不得不假设 Price 是一个小数,它确实有一个带有格式参数的 ToString。它是什么类型的?
【解决方案3】:

最好的办法是在视图模型上使用 DataAnnotations 显示格式属性。像这样的:

[DisplayFormat(DataFormatString = "{0:n}")]

然后使用 Html.EditorFor(model => model.Price) 来渲染输入。

【讨论】:

    【解决方案4】:

    您是否尝试过使用mode.Price.ToString() 并在 ToString 方法中指定所需的格式字符串?

    【讨论】:

    • 方法 'ToString' 没有重载需要 1 个参数
    • 抱歉 - 刚刚注意到您正在使用我认为不接受格式的 TextBoxFor 版本。
    【解决方案5】:

    这可能会有所帮助。

    private DateTime hDay;  
         [DisplayName("Hire Date")]  
         [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]  
         public DateTime HireDate  
         {  
           get  
           {  
             if (hDay == DateTime.MinValue)  
             {  
               return DateTime.Today;  
             }  
             else  
               return hDay;  
           }  
           set  
           {  
             if (value == DateTime.MinValue)  
             {  
               hDay = DateTime.Now;  
             }  
           }  
         }
    

    我们也可以这样用

    @Html.TextBoxFor(m => m.MktEnquiryDetail.CallbackDate, "{0:dd/MM/yyyy}")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多