I have following decimal field:
[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public decimal MyDecimal { get; set; }
In my Razor view
<td>Price</td>
<td>
@Html.EditorFor(model => model.MyDecimal, new { htmlAttributes = new { @class = "form-control decimal-small inline" } })
@Html.ValidationMessageFor(model => model.MyDecimal, "", new { @class = "text-danger" })
</td>
I want that users can only put a max of 2 number behind the decimal seperator. In many post I see that the DisplayFormat should work but it doesn't do anything in edit mode. In my edit field I can still put more than 2 numbers behind the seperator
I also tried
[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public decimal MyDecimal { get; set; }
Still no difference.
I think that you expect different thing that the [DisplayFormat] attribute does. This attribute says, how the data should be DISPLAYED, not entered. Your solution works, and your number is displayed with applied formatting, isn't it? What you're trying to achieve is an input mask, which is a client-side feature. See the following links to find out more about it:
Edit:
I've performed a quick test ViewModel:
[DisplayFormat(DataFormatString = "{0:0.00}",ApplyFormatInEditMode = true)]
public decimal Test {
get { return (decimal) 1.345; } }
and view :
@Html.EditorFor(model=>model.Test, new { htmlAttributes = new { @class = "form-control decimal-small inline" } })
As an alternative, you could try:
@Html.TextBoxFor(model=>model.Test,"{0:0.00}")