Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

separate numbers by comma with asp.net mvc

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!

like image 768
user629161 Avatar asked Mar 28 '11 17:03

user629161


1 Answers

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.

like image 197
Michael Gattuso Avatar answered Nov 02 '22 22:11

Michael Gattuso