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)
什么文化解析过程中被使用? – 2013-04-10 05:43:24
@JonSkeet,在控制器中检查“System.Threading.Thread.CurrentThread.CurrentCulture”显示“en-US” – 2013-04-10 06:25:47