Z .
Z .

Reputation: 12837

ASP.NET MVC 4 currency field

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?

Upvotes: 9

Views: 13055

Answers (3)

Piotr Kula
Piotr Kula

Reputation: 9811

You can also set edit mode to false. Then it will only show the decimal value while text will be formatted.

ApplyFormatInEditMode = false

Upvotes: 0

Mahesh Subramanian
Mahesh Subramanian

Reputation: 26

You can use System.ComponentModel.DataAnnotations.RegularExpressionAttribute.

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

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);
    }
}

Add this binder for Foo type at Application_Start:

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

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");

Now you will get validation error message if input value will not be correct currency amount (e.g. $10F.0).


BTW I think it's better to use ApplyFormatInEditMode = false than implement all this stuff to help MVC bind your custom formatted string.

Upvotes: 8

Related Questions