【问题标题】:Parse decimal in view model在视图模型中解析十进制
【发布时间】:2011-08-09 09:51:46
【问题描述】:

我正在用 ASP.NET MVC 3 开发一个网站。

房产

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

查看

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

视图将 Cost 呈现为 1000,00(例如)。问题是,验证需要一个点而不是逗号。如何输出 1000.00 而不是 1000,00?或者反转验证以接受逗号而不是点?

编辑。我在 web.config 中将全球化设置为 sv-SE(瑞典)。

【问题讨论】:

    标签: c# .net asp.net-mvc-3 decimal


    【解决方案1】:

    您需要编写一个自定义模型绑定器来执行此操作。

    /// <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 方法中

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

    【讨论】:

    • 感谢您的片段!奇迹般有效。我在使用双精度值而不是小数时遇到了问题,并且正在使用 [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#,0}")] 属性,它将双精度值格式化为没有小数的货币。感觉有点傻,框架默认不处理这些。
    【解决方案2】:

    问题是在我的国家解析小数点分隔符也是逗号:

    我发现了一些不太好的解决方法:

    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】:

      您能否仅更改 DataFormatString 以便它使用点来格式化数字,例如{0:0.00},还是类似的?

      【讨论】:

      • 格式化不是问题,是验证会失败
      猜你喜欢
      • 2015-07-03
      • 2022-11-16
      • 1970-01-01
      • 2020-01-20
      • 2018-07-18
      • 1970-01-01
      • 2010-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多