0

I'm trying to use the EditorFor in MVC 5 to display a numeric value with commas, if the number is over 999. Here's my code:

The viewmodel:

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

The template:

@Html.EditorFor(modelItem => Model.Rows[i].CostItem.Amount, new { @id = "CostAmt_" + i, @name = "monthCost" })

and then the custom template:

@model decimal

@Html.TextBox("", (Model),
new { @class = "monthCost form-control" })

10,000.00 shows up fine if I use DisplayFor but EditorFor displays 10000.00 in the textbox. What am I missing here?

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
TrevorGoodchild
  • 978
  • 2
  • 23
  • 49
  • You need `ApplyFormatInEditMode = true`, but that only displays the initial value with a comma (if the user edits it, a comma is not added automatically). And the you would need a custom ModelBinder to bind the value in the POST method. You might be interested in [mvc-numericinput](https://github.com/stephenmuecke/mvc-numericinput) if you want formatted values in forms –  Jul 05 '18 at 22:14
  • ApplyFormatInEditMode = true doesn't fix it. I have some scripts in the page to handle adding the commas when the user types, I'm just trying to get it to format properly when the value comes back from the DB. – TrevorGoodchild Jul 06 '18 at 12:07
  • 1
    Because you need to use `EditorFor()` in your template (or use `@Html.TextBoxFor (m => m, "{0:N2}", new { ... })` –  Jul 06 '18 at 12:10
  • Wow, I feel like that was the only thing I didn't try. Thank you Stephen! – TrevorGoodchild Jul 06 '18 at 12:17

1 Answers1

0

you should set ApplyFormatInEditMode to true

j03p
  • 321
  • 3
  • 11