Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
[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) %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...