在视图模型解析十进制 [英] Parse decimal in view model

查看:128
本文介绍了在视图模型解析十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的ASP.NET MVC 3的站点。

I'm developing a site in ASP.NET MVC 3.

属性

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

查看

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

视图呈现费用作为1000,00(例如)。问题是,验证要求逗号的一个点来代替。我怎么能输出1000.00代替1000,00?或反向验证接受逗号,而不是一个点?

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?

编辑。我给自己定的全球化在我的web.config中SV-SE(瑞典)。

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;
    }
}

在您的Global.asax文件,添加以下到您的Application_Start方法

In your Global.asax file, add the following to your Application_Start Method

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());

这篇关于在视图模型解析十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆