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

与世无争的帅哥 提交于 2019-12-17 12:16:02

问题


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?


回答1:


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



回答2:


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

What does "inordinately inelegant" mean?



来源:https://stackoverflow.com/questions/5080451/how-should-i-use-editorfor-in-mvc-for-a-currency-money-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!