19

If I have a decimal value in a field, and I am trying to display on a page, how do I format it (I would use string.format in web forms):

@Html.DisplayFor(Function(modelItem) String.Format("{0:n0}",currentItem.QualityM1))

That errors in VS2010 with the messae: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Brandon
  • 68,708
  • 30
  • 194
  • 223
Mark
  • 7,778
  • 24
  • 89
  • 147
  • See [this](http://stackoverflow.com/questions/7087495/using-razor-view-engine-how-do-i-format-a-decimal-value-to-have-commas-and-two). –  Mar 15 '12 at 14:23
  • Hi - please ignore this - just found the answer - for anyone else looking, I simply replaced it with: @String.format("{0:n0}",currentItem.QualityM1) Thanks again, Mark – Mark Mar 15 '12 at 14:24

3 Answers3

27

I wouldn't do this inside the view. It would be better to centralize this and provide this information as metadata as below:

public class Foo { 

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

Then use this as usual:

@Html.DisplayFor(m => m.Bar)
Al Lelopath
  • 6,448
  • 13
  • 82
  • 139
tugberk
  • 57,477
  • 67
  • 243
  • 335
15

Do you need to use Html.DisplayFor?

Otherwise you can just do:

@String.Format("{0:n0}",currentItem.QualityM1)
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
4

dont do in DisplayFor... in the class set the atributte like this one.

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N2}")]
    public virtual decimal Valor
    {
        get;
        set;
    }