Data Annotation for currency format not working

前端 未结 2 571
遥遥无期
遥遥无期 2021-01-27 15:34

In my ASP.NET MVC Core web project on VS2015, the following model is displaying data as, e.g., 15481 instead of $15,481 even though I\'m using [D

2条回答
  •  故里飘歌
    2021-01-27 16:02

    A [DisplayFormat] attribute is only respected when using @Html.DisplayFor() or @Html.EditorFor(). It is ignored when using TextBoxFor().

    In addition, if you wanted to use it with @Html.EditorFor(r => r[i].SaleAmount) you need to modify the attribute to include the ApplyFormatInEditMode property

    [DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
    public float? SaleAmount { get; set; }
    

    however that would be of little use to you, because although it would display in the textbox correctly, it will not bind back to you float property unless you were also to create a custom model binder which converted (say) "$15,481" back to a float

提交回复
热议问题