2013-04-10 49 views
0

我有這個視圖模型類與價格屬性。Convert.ToDecimal失敗,並說輸入字符串的格式不正確

問題是如果用戶輸入值$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 
} 

我在模型綁定Input string was not in a correct format註冊此十進制模型綁定在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; 
    } 

錯誤

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

什麼文化解析過程中被使用? – 2013-04-10 05:43:24

+0

@JonSkeet,在控制器中檢查「System.Threading.Thread.CurrentThread.CurrentCulture」顯示「en-US」 – 2013-04-10 06:25:47

回答

0

增加額外的十進制轉換,如果格式是貨幣

由於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); 
}