DisplayFormat for TextBoxFor in MVC

后端 未结 5 527
孤独总比滥情好
孤独总比滥情好 2020-12-09 02:56

I need to round off 4 digit decimal to 2 digits and show in MVC 3 UI

Something like this 58.8964 to 58.90

Tried following this How should I

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 03:15

    You should use Html.EditorFor instead of Html.TextBoxFor if you want the custom format to be taken into account:

    @Html.EditorFor(m => m.TotalAmount)
    

    Also make sure that you have set ApplyFormatInEditMode to true:

    [DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
    public decimal? TotalAmount { get; set; }
    

    The DisplayFormat attribute is intended to be used only with templated helpers such as EditorFor and DisplayFor. This is the recommended approach instead of using TextBoxFor.

提交回复
热议问题