1

我想知道如何将强类型视图价格字段转换为 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;" })%>
4

5 回答 5

3

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

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

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

<%= Html.TextBox("Price", string.Format("{0:n}", Model.Price)) %>
于 2011-07-18T15:18:16.900 回答
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;" })%>
于 2011-07-18T15:18:10.263 回答
2

您最好的选择是在您的视图模型上使用 DataAnnotations 显示格式属性。像这样的东西:

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

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

于 2011-07-18T15:18:10.650 回答
0

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

于 2011-07-18T15:23:14.317 回答
0

这可能会有所帮助。

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}")
于 2015-10-10T18:26:13.730 回答