Formatting currency using display template in MVC

ThdK picture ThdK · Jun 3, 2013 · Viewed 20.2k times · Source

I found this post about Display and EditorTemplates for MVC:

http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html

It creates a display template to easily display a decimal formatted with currency sign.

The model used in the example:

public class TestModel
{
    public decimal Money { get; set; }
}

The display template:

Views/Shared/DisplayTemplates/decimal.cshtml:

@model decimal

@{
    IFormatProvider formatProvider = 
        new System.Globalization.CultureInfo("en-US");
    <span class="currency">@Model.ToString("C", formatProvider)</span>
}

In my website I have a helper class with a method to retrieve a formatted currency string from a decimal, so I would replace the above with something like:

@model decimal
@(MyHelperClass.GetCurrencyString(Model))

And finally the view where we want to see the formatted currency:

@model TestModel    
@Html.DisplayFor(e => e.Money)

Output:

<span class="currency">$3.50</span>

I can implement this without any problem. But of course i have different views where i want to view a formatted currency. But in some cases I don't want to show the currency sign.

My question now is how i should implement this small variation without to much overkill in code.

Here is my current implementation:

I've changed my display template to this:

@model decimal

@{
    bool woCurrency = (bool)ViewData["woCurrency"]; 
 }

@(MyHelperClass.GetCurrencyString(Model)Model,woCurrency))

Of course i've also changed to GetCurrencyString method to accept this additional attribute.

In my view I now have to provide this attribute too:

@Html.DisplayFor(m => m.Money, new { woCurrency = true })

So actually I everything works like it should work. But somehow I don't like this sollution that makes the view more complex.

My question to you: Is there any other method to implement something like this? Or any advice to possible optimise my current sollution?

Thanks!

Answer

Husein Roncevic picture Husein Roncevic · Jun 3, 2013

You need to apply DisplayFormat attribute to your Money property. For example:

[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Money { get; set; }

For more information have a look at these two links:

  1. DisplayFormatAttribute.DataFormatString (The example at the bottom of the page uses currency formatting as an example)
  2. ASP.NET MVC - DisplayFormat attribute