Dustin Harrell
Dustin Harrell

Reputation: 627

Can't get Currency formatted textbox into a decimal Model (MVC)

Inside my application I have a text box that has javascript convert values into a currency format. This is mandatory and nonnegotiable.

ie. 5.50 becomes $5.50 and -5.50 becomes ($5.50)

When I try to save I get a validation error because $5.50 is not valid for the ViewModel

//View file
 @Html.CustomEditorFor(m => m.CurrentTotal, "currency")

//Controller file. First thing in the controller method called
if (ModelState.IsValid)
{
//... not getting to this
}

//ViewModel file
[Display(Name = "Current Total:")]
public decimal CurrentTotal
{
  get
  {
    return PropertyDictionary.GetDecimal("CurrentTotal", 0).Value;
  }
  set
  {
    PropertyDictionary.SetDecimal("CurrentTotal", value);
  }
}

I was wondering how I remove non-numeric excluding "." from the text box before it goes to the model and causes the ModelState to be invalid.

Once again I have inherited this application and am learning so I appreciate the time and patience!

Upvotes: 0

Views: 1673

Answers (2)

Dustin Harrell
Dustin Harrell

Reputation: 627

I still don't know how to do this in MVC (though it looks like I should use custom model binders) I made a work around for this problem.

 $(document).submit(function () {
        $("input[type=text].currency").each
        (
            function () {
                $(this).val($(this).val().toString().replace('(', '-').replace("$", '').replace(")", ''));
            }
        );
    });

Hope this helps someone in the future.

Upvotes: 0

ElliotSchmelliot
ElliotSchmelliot

Reputation: 8402

How about a call such as

double.Parse(currencyValue, NumberStyles.Currency);

as suggested in this related link. Check out NumberStyles for additional options.

Upvotes: 2

Related Questions