Parse decimal in view model

2019-04-23 18:48发布

问题:

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).

回答1:

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


回答2:

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



回答3:

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