Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 758
Thomas Langston Avatar asked Feb 22 '11 15:02

Thomas Langston


2 Answers

[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) %>
like image 158
Darin Dimitrov Avatar answered Oct 13 '22 08:10

Darin Dimitrov


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

What does "inordinately inelegant" mean?

like image 21
John Farrell Avatar answered Oct 13 '22 09:10

John Farrell