1

I'm using Entity Framework v6.1.3 (code first) and ASP.NET MVC v5.2.3

I know I can use DisplayFormatAttribute in a decimal datatype like this

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

Now what I need is to apply this attribute automatically to every decimal in each entity.

Is this possible?

I had a similar requirement that every decimal must have a precision of 20,8 and I solved this using this code

public class EntitiesContext : DbContext
{
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      // Set all decimals data types by default as Decimal(20, 8)
      modelBuilder.Properties<decimal>().Configure(c => c.HasPrecision(20, 8));
   }
}

So I wonder if is it possible to assign automatically the DisplayFormatAttribute.

vcRobe
  • 1,671
  • 3
  • 17
  • 35

3 Answers3

3

You can create display template for decimal type and put it to Views/Shared/DisplayTemplates folder:

@model System.Decimal
<span>  
    @Model.ToString("n2")
</span>

And in view just use DisplayFor or DisplayForModel methods:

@Model.DisplayFor(m => m.Foo)

Further reading: What are Display and Editor Templates?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
2

You can create a DisplayTemplate for the decimal type is every decimal is going to be formatted the same way.

from ASP.NET MVC display and editor templates

Defining custom templates

We can override the default templates by placing our custom display templates into the path Views/Shared/DisplayTemplates/.cshtml. They are structured like any MVC partial view. An example usage could be adding a dollar sign to the front of a decimal’s value. Model

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

Views/Shared/DisplayTemplates/decimal.cshtml

@model decimal

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

view

@model TestModel

@Html.DisplayFor(e => e.Money)
Fran
  • 6,440
  • 1
  • 23
  • 35
0

Doing a deep search I found the answer

It can't be done

Here's the answer

Can attributes be added dynamically in C#?

Community
  • 1
  • 1
vcRobe
  • 1,671
  • 3
  • 17
  • 35