问题
I am working on an MVC2 appication.
I use data annotations to validate data (both client side and server side). I have several fields in my model that only allows decimal values. As soon as a user types a decimal values I want it to be converted to comma seperated more readable format. For instance 1200 should be formatted to 1,200 while 500 should stay as it is.
Here is my model:
public virtual GrossFee? Fee { get; set; }
And here is how it is on the view:
%: Html.TextBoxFor(model => model.GrossFee)%>
Any ideas regarding this will be highly appreciated.
Thanks!
回答1:
Instead of the Html.TextBoxFor
you can use the Html.EditorFor
and have the view respect the data annotations like this:
Model:
(I don't know what GrossFee?
is but lets assume its a decimal)
[DisplayFormat(DataFormatString = "{0:0,0}")]
public virtual Decimal? Fee { get; set; }
View:
Html.EditorFor(model => model.GrossFee)
You may also need to tweak the HtmlEncode and ApplyFormatInEditMode to suit your particular application.
Anything that converts the textbox contents into comma grouped numbers as soon as entered (I.e. before the post back) would need to be javascript based.
回答2:
[DisplayFormat(DataFormatString = "{0:n}")]
public virtual GrossFee? Fee { get; set; }
hope this can help you
回答3:
drPastDateDetail[strMS] = decValue.ToString();
Instead of the above line, if you wish to display the numeric value with a comma, the following code will help you-
String Test = String.Format("{0:#,#.##}",decValue);
drPastDateDetail[strMS]=Test;
回答4:
I put this line of code in my Controller
public ActionResult Index()
{
TempData["TotalPaid"] = totalAmountPaid.ToString("#,###.00");
}
And i put this in my View
<table>
<tr>
<td style="color:green; font-weight:bold" >
Amount Paid: $@TempData["TotalPaid"]
</td>
</tr>
</table>
回答5:
You should be able to use a Format within tostring
var foo = 1200.2;
var bob = foo.ToString("#,###.00##");
来源:https://stackoverflow.com/questions/5462489/separate-numbers-by-comma-with-asp-net-mvc