How should I use EditorFor() in MVC for a currency/money type?

前端 未结 2 1149
清酒与你
清酒与你 2020-12-03 13:53

In my view I have the following call.

<%= Html.EditorFor(x => x.Cost) %>

I have a ViewModel with the following code to define Cost

2条回答
  •  伪装坚强ぢ
    2020-12-03 14:55

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

    and in your view:

    <%= Html.EditorFor(x => x.Cost) %>
    

    and that's all.

    You will probably want to apply a custom CSS class. You could do this:

    <%= Html.EditorFor(x => x.Cost) %>

    and then have in your css:

    .currency input {
        /** some CSS rules **/
    }
    

    or write a custom DataAnnotationsModelMetadataProvider which will allow you to:

    [DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
    [HtmlProperties(CssClass = "currency")]
    public decimal Cost { get; set; }
    

    and then in your view:

    <%= Html.EditorFor(x => x.Cost) %>
    

提交回复
热议问题