我应该如何使用EditorFor()在MVC的货币/货币类型? [英] How should I use EditorFor() in MVC for a currency/money type?

查看:134
本文介绍了我应该如何使用EditorFor()在MVC的货币/货币类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,我有以下电话。

 <%= Html.EditorFor(X => x.Cost)%GT;

我有以下code一个ViewModel定义成本。

 公共小数成本{搞定;组; }

然而,这显示小数(如0.0000)后,用四位数字的十进制值。我知道 Decimal.ToString的(G)的 MSDN ),这似乎解决了这个问题,但我不确定在哪里应用它。

一个解决方案似乎是创建一个局部视图Currency.aspx。

 <%@控制语言=C#继承=System.Web.Mvc.ViewUserControl<&十进制GT; %GT;
<%= Html.TextBox(Model.ToString(G),新{@class =货币})%GT;

和一个 [UIHint(货币)] 在我的视图模型。

这看起来不太优雅。我认为这个问题已经解决了MVC框架或C#整齐的地方,但我不知道更清洁的解决方案。

什么是处理MVC编辑货币值的适当方法?


解决方案

  [DisplayFormat(DataFormatString ={0:F2},ApplyFormatInEditMode = TRUE)]
公共小数成本{搞定;组; }

和在您的视图:

 <%= Html.EditorFor(X => x.Cost)%GT;

和这一切。

您可能希望应用自定义CSS类。你可以这样做:

 < D​​IV CLASS =货币>
    &所述;%= Html.EditorFor(X => x.Cost)%GT;
< / DIV>

然后在你的CSS:

  .currency输入{
    / **一些CSS规则** /
}

或<一个href=\"http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-_2D00_-ASP.Net-MVC-2.0-Beta_2D00_1.aspx\">write自定义DataAnnotationsModelMetadataProvider 这将允许您:

  [DisplayFormat(DataFormatString ={0:F2},ApplyFormatInEditMode = TRUE)]
[HtmlProperties(的CssClass =货币)]
公共小数成本{搞定;组; }

,然后在您的视图:

 &LT;%= Html.EditorFor(X =&GT; x.Cost)%GT;

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?

解决方案

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

这篇关于我应该如何使用EditorFor()在MVC的货币/货币类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆