Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC data annotation for currency format

Tags:

asp.net-mvc

I have following POCO with Cost as float.

public class CostChart
{
    public string itemType { get; set; }
    public float? Cost{ get; set; }

}

I need to return Cost in currency format e.g.

$U 4.882,50.

What data annotation should I use?

This is how I am displaying in my view.

<td>@Model.Cost</td>
like image 940
immirza Avatar asked Apr 30 '15 18:04

immirza


4 Answers

Have you tried using DataType.Currency:

public class CostChart {     public string itemType { get; set; }     [DataType(DataType.Currency)]     public float? Cost{ get; set; }  } 

Alternatively, you could use DataFormatString like this:

[DisplayFormat(DataFormatString = "{0:C0}")]` public float? Cost{ get; set; } 

But I prefer to set the display format with EditorFor. Here's a great tutorial on Extending Editor Templates for ASP.NET MVC tutorial.

That way, you write the display logic of your currencies in just ONE place, and you don't need to add that extract annotation every single time you want to display a currency amount.

--Edit

To make it work in EditorFor, you can also add ApplyFormatInEditMode = true to the end of the DataFormatString making the line as:

[DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)] 
like image 179
Cacho Santa Avatar answered Oct 01 '22 05:10

Cacho Santa


Try using:

 [DisplayFormat(DataFormatString = "{0:C0}")] 

Visit this post https://stackoverflow.com/a/19800496/3642086

like image 30
Márcio Gonzalez Avatar answered Oct 01 '22 06:10

Márcio Gonzalez


try this :

public class CostChart
  {
    public string itemType { get; set; }

    [DataType(DataType.Currency)]
    public float? Cost{ get; set; }
  }

if you still do not see $ symbol, in web.config under write this line of code

<globalization culture ="en-us"/>
like image 41
Rachit Thakur Avatar answered Oct 01 '22 04:10

Rachit Thakur


All right, when we talking about data annotations, there's two things to take in account:

The Data Annotation, which is:

[DisplayFormat(DataFormatString = "{0:C0}")]
public decimal? Cost{ get; set; }

And the tag in Razor pages, which is:

@Html.DisplayFor(model => model.Cost)

If you don't use "DisplayFor", data annotations is useless.

Another detail, if you want the decimal place, you should remove the last "0" after "C", as follow:

[DisplayFormat(DataFormatString = "{0:C}")]

Hope it helps you and good luck!

like image 32
Thiago Araujo Avatar answered Oct 01 '22 06:10

Thiago Araujo