开发者

String Formatting in C# for Strongly typed view

I want to know how can I convert a strong typed v开发者_如何转开发iew 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:

<%: 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:

[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:

<%: 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. Something like this:

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

And then use the Html.EditorFor(model => model.Price) to render the input.


Have you tried using mode.Price.ToString() and specifying your desired format string in the ToString method?


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}")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜