ASP.NET MVC data annotation for currency format

后端 未结 5 1818
栀梦
栀梦 2020-12-10 10:49

I have following POCO with Cost as float.

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

}

相关标签:
5条回答
  • 2020-12-10 11:22

    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)]
    
    0 讨论(0)
  • 2020-12-10 11:22

    Check out this article(Codeculous.) an alternate way to validate and display the respective currency symbols without setting Globalization and just by adding the data annotations DataType(DataType.Currency).

    0 讨论(0)
  • 2020-12-10 11:26

    Try using:

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

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

    0 讨论(0)
  • 2020-12-10 11:38

    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"/>
    
    0 讨论(0)
  • 2020-12-10 11:41

    You can do in RazorView

    @string.Format("{0:0,0.00,00}", Model.Cost)
    
    0 讨论(0)
提交回复
热议问题