开发者

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. 开发者_Python百科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!


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.


[DisplayFormat(DataFormatString = "{0:n}")]
public virtual GrossFee? Fee { get; set; }

hope this can help you


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;


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>


You should be able to use a Format within tostring

var foo = 1200.2;
var bob = foo.ToString("#,###.00##");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜