I'm developing a site in ASP.NET MVC 3.
Property
[DisplayName("Cost"), DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal Cost { get; set; }
View
@Html.EditorFor(x => x.Cost)
The view renders Cost as 1000,00 (for example). The problem is, validation demands a point instead of a comma. How can I output 1000.00 instead of 1000,00? Or reverse the validation to accept the comma instead of a point?
Edit. I've set globalization in my web.config to sv-SE (Sweden).
Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.
To convert a Decimal value to its string representation using a specified culture and a specific format string, call the Decimal. ToString(String, IFormatProvider) method.
Converts the string representation of a number to its Decimal equivalent.
A user can also convert a Decimal value to a 32-bit integer by using the Explicit assignment operator. Syntax: public static int ToInt32 (decimal value); Here, the value is the decimal number which is to be converted. Return Value: It returns a 32-bit signed integer equivalent to the specified value.
You'll need to write a Custom Model Binder to do this.
/// <summary>
/// http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx
/// </summary>
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.CurrentCulture);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
In your Global.asax file, add the following to your Application_Start Method
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
The problem is on parse decimal separator in my country too is comma:
I found some workaround not so nice:
http://rebuildall.umbraworks.net/2011/03/02/jQuery_validate_and_the_comma_decimal_separator
http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With