Search code examples
c#asp.net-mvccurrency

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


In my view I have the following call.

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

I have a ViewModel with the following code to define Cost.

public decimal Cost { get; set; }

However this displays a decimal value with four digits after the decimal (e.g. 0.0000). I am aware of Decimal.toString("G") (MSDN) which appears to solve this issue, but I'm uncertain of where to apply it.

One solution seems to be create a partial view "Currency.aspx".

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Decimal>" %>
<%= Html.TextBox(Model.ToString("g"), new { @class = "currency" }) %>

And a [UIHint("Currency")] in my ViewModel.

This seems inelegant. I assume that this problem has been solved tidily somewhere in the MVC framework or C# but I am unaware of cleaner solutions.

What is the appropriate way to handle editing currency values in MVC?


Solution

  • [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) %>