在我看来,我有以下调用。
<%= Html.EditorFor(x => x.Cost) %>
我有一个包含以下代码的ViewModel来定义成本。
public decimal Cost { get; set; }
但是,这会显示小数后面有四位数的十进制值(例如0.0000)。我知道Decimal.toString("G")
(MSDN)似乎解决了这个问题,但我不确定在哪里应用它。
一种解决方案似乎是创建一个局部视图"Currency.aspx“。
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Decimal>" %>
<%= Html.TextBox(Model.ToString("g"), new { @class = "currency" }) %>
在我的ViewModel里还有一个[UIHint("Currency")]
。
这似乎很不雅观。我假设这个问题已经在MVC框架或C#中的某个地方整齐地解决了,但我不知道有更干净的解决方案。
在MVC中编辑货币值的合适方式是什么?
发布于 2011-02-22 23:59:36
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal Cost { get; set; }
在你看来:
<%= Html.EditorFor(x => x.Cost) %>
仅此而已。
您可能希望应用自定义CSS类。你可以这样做:
<div class="currency">
<%= Html.EditorFor(x => x.Cost) %>
</div>
然后在你的css中添加:
.currency input {
/** some CSS rules **/
}
或允许您执行以下操作的write a custom DataAnnotationsModelMetadataProvider:
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
[HtmlProperties(CssClass = "currency")]
public decimal Cost { get; set; }
然后在您的视图中:
<%= Html.EditorFor(x => x.Cost) %>
发布于 2011-02-22 23:56:31
如果您使用的是EditorFor模板,则这是合适的方法。
“异常不雅”是什么意思?
https://stackoverflow.com/questions/5080451
复制相似问题