Paul
Paul

Reputation: 5934

Why doesn't DataFormatString work in my MVC application?

I have a numeric field that is defined as a decimal. I'm trying to show it as an integer value though.

My model:

[Column(CanBeNull = true, DbType = "numeric", Name = "VHCL_ODOMTR")]
  [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:f0}", HtmlEncode = false, NullDisplayText = "")]
  [Display(Name = "Odometer")]
  public decimal? VehicleOdometer { get; set; }

My Razor:

@Html.TextBoxFor(model => model.VehicleOdometer)

My output is always a text box with ONE decimal. I cannot make it stop doing this. I've tried {0:D}, {0:#}, and using a capital F instead of lowercase. Even trying "F9" shows 1 decimal and not 9. Seems to completely ignore the DataFormatProperty.

Upvotes: 0

Views: 1114

Answers (1)

John H
John H

Reputation: 14640

This is because DisplayFormatAttribute is designed to be used with templated view helpers (i.e. Html.EditorFor and Html.DisplayFor). So, in order for this to work, you need to use:

@Html.EditorFor(model => model.VehicleOdometer)

Upvotes: 1

Related Questions