Question

I'm creating an ASP.NET MVC3 application, and I have a form where user have to enter a price. For improving user experience, I'd like to implement a thousand separator. I've done it, you can see it working on this FIDDLE.

BUT

This Price field is part of a model and is declared in my Model file as

public decimal? Price {get; set;}

When I submit my form, Price is always null. However, it has the value entered in the form if I remove my thousand separator. This is because Price seems to be interpreted as a string, and not as a decimal, so MVC doesn't match the two properties (I suppose).

So, how can force MVC to recognize my value as a correct decimal and submit a model with the price entered by the user ?

Thanks for your help.

Was it helpful?

Solution

I believe it will be easier to make the following: you can either create a hidden field on the form and store the number without separators or you can remove separators right before submitting the form.

Example:

$("#target-form").submit(function(event) {
  value_with_separators = $('.thousandSeparator').val();
  clean_value = value_with_separators.replace(/\s+/g, '');
  $('.thousandSeparator').val(clean_value);
});

There's also another way. You can implement custom ModelBinder and perform required conversions there. Here is a link to a related question with code samples.

Hope it helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top