ASP.NET MVC 4货币字段 [英] ASP.NET MVC 4 currency field
问题描述
我在货币字段的网页上收到错误消息(字段金额必须为数字").这是因为有美元符号($ 50.00).
I get an error ("The field Amount must be a number") on my web page on a currency field. It is because of the dollar sign ($50.00).
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:c}", ApplyFormatInEditMode = true)]
public decimal Amount { get; set; }
@Html.EditorFor(model => model.Amount)
如果我想保留美元符号,还需要做什么?
What else do I need to do if I want to keep the dollar sign?
推荐答案
Default MVC model binder cannot parse value formatted for display. So, you should write your own model binder and register it for this type (suppose type name is Foo):
public class FooModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result = bindingContext.ValueProvider.GetValue("Amount");
if (result != null)
{
decimal amount;
if (Decimal.TryParse(result.AttemptedValue, NumberStyles.Currency, null, out amount))
return new Foo { Amount = amount };
bindingContext.ModelState.AddModelError("Amount", "Wrong amount format");
}
return base.BindModel(controllerContext, bindingContext);
}
}
在Application_Start上为Foo类型添加此绑定器:
Add this binder for Foo type at Application_Start:
ModelBinders.Binders.Add(typeof(Foo), new FooModelBinder());
啊,最后一件事-从金额文本框中删除data-val-number
属性(否则,您将继续看到不是数字的消息):
Ah, and last thing - remove data-val-number
attribute from amount textbox (otherwise you will continue seeing message that it's not a number):
$("#Amount").removeAttr("data-val-number");
现在,如果输入值不正确的货币金额(例如$10F.0
),您将收到验证错误消息.
Now you will get validation error message if input value will not be correct currency amount (e.g. $10F.0
).
顺便说一句,我认为使用ApplyFormatInEditMode = false
比实现所有这些东西来帮助MVC绑定自定义格式的字符串更好.
BTW I think it's better to use ApplyFormatInEditMode = false
than implement all this stuff to help MVC bind your custom formatted string.
这篇关于ASP.NET MVC 4货币字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!