开发者

Parse decimal in view model

开发者 https://www.devze.com 2023-03-27 05:41 出处:网络
I\'m developing a site in ASP.NET MVC 3. Property [DisplayName(\"Cost\"), DisplayFormat(DataFormatString = \"{0:F2}\", ApplyFormatInEditMode = true)]

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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消