Mark
Mark

Reputation: 7818

Format a decimal in a view

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.

Upvotes: 19

Views: 44353

Answers (3)

user3302942
user3302942

Reputation: 51

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;
    }

Upvotes: 4

tugberk
tugberk

Reputation: 58494

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)

Upvotes: 27

Richard Dalton
Richard Dalton

Reputation: 35803

Do you need to use Html.DisplayFor?

Otherwise you can just do:

@String.Format("{0:n0}",currentItem.QualityM1)

Upvotes: 15

Related Questions