Sunday, October 4, 2009

String formatting in ASP.NET

I'm doing some pretty basic string formatting stuff while playing with an ASP.NET MVC application. The C# syntax for string formats in ASP.NET is pretty straight forward. At the moment I'm more interested in getting the controllers working - I can play with making the view pretty later :)

String formatting allows you to render common text formats such as:
  • Dates
  • Currency
  • alignment
  • numbers such as reals, decimals, scientific formats, floats, hex
Some basic examples that I've played with are:

 Purchase Price:  <%= Html.Encode(String.Format("{0:c}", Model.PurchasePrice))%>

would render to the HTML page as Purchase Price: $49.95


Release Date: <%= Html.Encode(String.Format("{0:d}", Model.ReleaseDate)) %>

would render to the HTML page as  Release Date: 7/11/1999

And because it's rendering in string format, if there is no string passed, then nothing is returned (it doesn't fall over). I haven't yet played with what happens if it can't format into a particular value as the data was validated before saving. But like a dutiful coder, that's what my unit tests will be for (when I wite them for this page now that the basic code is there.)


http://idunno.org/archive/2004/07/14/122.aspx has a fantastic overview of string formatting tags

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.