String Extension Methods in Razor

The new Razor view engine contains several handy extension methods you can use in your views.  These methods mostly deal with either detecting if a string value can be converted to a particular type, or converting string values to a particular type.  For instance, the following code checks to see if a querystring value is a decimal, and if so, to format it as a currency:


@{
    if (Request.QueryString["amount"].IsDecimal())
    {
        @Request.QueryString["amount"].AsDecimal().ToString("c")W
    }
    else
    {
        @: Amount is not a valid number
    }
}

There are Is(Type), and As(Type) methods for bools, datetimes, decimals, floats, and ints. All of the As(Type) conversion methods take in an optional second parameter that can serve as the default value in case the conversion is not successful.

These extension methods are handy and can save some time and lines of code when dealing with strings.  They are in the System.Web.WebPages namespace, which new projects in MVC3 and Webmatrix automatically reference, so you do not need to worry about adding any using statements into your views in order to take advantage of them.  If you want to take advantage of them in your views, you can simply add a using statement to System.Web.WebPages.