简体   繁体   English

C# 中的字符串格式,用于强类型视图

[英]String Formatting in C# for Strongly typed view

I want to know how can I convert a strong typed view Price field in to 2 digit specifier like i have got a money field in my db which converts for instance 15 into 15.0000, i juts want to display 15.00 in the view, below is the code:我想知道如何将强类型视图价格字段转换为 2 位说明符,就像我的数据库中有一个货币字段,例如将 15 转换为 15.0000,我想在视图中显示 15.00,下面是代码:

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

I tried something like with no success:我尝试了类似但没有成功的方法:

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

You can put an attribute on the model something like:您可以在 model 上放置一个属性,例如:

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

If you don't want to do that then you will need to use the 'old' style text box:如果您不想这样做,则需要使用“旧”样式文本框:

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

Try this:尝试这个:

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

Update:更新:

You also missed a comma in your original syntax which could be all that's stopping it from working that way too.您还错过了原始语法中的逗号,这可能也是阻止它以这种方式工作的全部原因。 Should have been:本来应该:

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

Also, for 2 decimal places, try it like this:此外,对于 2 位小数,请尝试如下:

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

Your best bet is to use a DataAnnotations display format attribute on your view model.最好的办法是在视图 model 上使用 DataAnnotations 显示格式属性。 Something like this:像这样的东西:

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

And then use the Html.EditorFor(model => model.Price) to render the input.然后使用 Html.EditorFor(model => model.Price) 来渲染输入。

this may help.这可能会有所帮助。

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

OR或者

we can use this way too我们也可以使用这种方式

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

Have you tried using mode.Price.ToString() and specifying your desired format string in the ToString method?您是否尝试过使用mode.Price.ToString()并在 ToString 方法中指定所需的格式字符串?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM