ASP.NET MVC 4 Currency Field

I get an error ("Amount field must be a number") on my web page in the currency field. This 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?

+7
source share
3 answers

Standard MVC model binding cannot parse a value formatted for display . So, you have to write your own connecting device and register it for this type (suppose the 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); } } 

Add this binder for type Foo to Application_Start:

 ModelBinders.Binders.Add(typeof(Foo), new FooModelBinder()); 

And, the last - remove the data-val-number attribute from the sum text field (otherwise you continue to see the message that this is not a number):

 $("#Amount").removeAttr("data-val-number"); 

You will now receive a validation error message if the input value is not the correct currency value (for example, $10F.0 ).


BTW I think it is better to use ApplyFormatInEditMode = false than to implement all these things to help MVC bind your own formatted string.

+7
source

You can use System.ComponentModel.DataAnnotations.RegularExpressionAttribute.

0
source

You can also set the editing mode to false. Then only the decimal value will be displayed, while the text will be formatted.

 ApplyFormatInEditMode = false 
0
source

All Articles