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

前端 未结 2 1130
清酒与你
清酒与你 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:47

    This is the appropriate way if you are using EditorFor templates.

    What does "inordinately inelegant" mean?

    0 讨论(0)
  • 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:

    <div class="currency">
        <%= Html.EditorFor(x => x.Cost) %>
    </div>
    

    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) %>
    
    0 讨论(0)
提交回复
热议问题