【问题标题】:Convert.ToDecimal Fails and says Input string was not in a correct formatConvert.ToDecimal 失败并说输入字符串的格式不正确
【发布时间】:2013-04-01 19:41:40
【问题描述】:

我有这个带有价格属性的视图模型类。

问题是如果用户输入值$200,150.90 它没有被格式化并发送到控制器。

十进制的默认模型格式化程序可能有什么问题?

public ItemViewModel
{

public string Name {get;set;}
[DisplayFormat(DataFormatString = "{0:c}")]
[RegularExpression(@"^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$"
ErrorMessage = "Enter a valid money value. 2 Decimals only allowed")]
public decimal? Price{ get; set; }
}

在视图中

@model ItemViewModel

@Html.TextBoxFor(m=>m.Price)

在控制器中

public ActionResult Save(ItemViewModel model)
{

 // model.Price is always null, even if it has value $200,150.90
}

我已经在Global.asax注册了这个十进制模型绑定器

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

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

模型绑定器中的错误Input string was not in a correct format

 Convert.ToDecimal("$200,150.90",CultureInfo.CurrentCulture)

【问题讨论】:

  • 解析过程中使用的是什么文化?
  • @JonSkeet,在控制器中检查此System.Threading.Thread.CurrentThread.CurrentCulture 显示en-US

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


【解决方案1】:

如果格式为货币,则添加额外的十进制转换

感谢Convert currency string to decimal?

 string currencyDisplayFormat=(bindingContext.ModelMetadata).DisplayFormatString;
 if (!string.IsNullOrEmpty(currencyDisplayFormat) 
                           && currencyDisplayFormat == "{0:c}")
 {
    actualValue = Decimal.Parse(valueResult.AttemptedValue,
                  NumberStyles.AllowCurrencySymbol | NumberStyles.Number, 
                  CultureInfo.CurrentCulture);

 }
 else
 {
        actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                        CultureInfo.CurrentCulture);
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多