Decimal parameter in view

I am developing a site in ASP.NET MVC 3.

The property

[DisplayName("Cost"), DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)] public decimal Cost { get; set; } 

View

 @Html.EditorFor(x => x.Cost) 

The view displays the cost as 1000.00 (for example). The problem is that validation requires a dot instead of a comma. How can I withdraw 1000.00 instead of 1000.00? Or cancel the check to accept a comma instead of a period?

Change I installed globalization in my web.config for sv-SE (Sweden).

+8
decimal c # asp.net-mvc-3
source share
3 answers

To do this, you need to write Custom Binder.

 /// <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 the Global.asax file, add the following to your Application_Start method

 ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); 
+10
source share

The problem is the decimal separator in my country, there is also a comma:

I found some workaround not very pleasant:

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

+3
source share

Can you not just change the DataFormatString so that it formats the number using a dot, for example. {0: 0.00} or similar?

0
source share

All Articles