我找到了解决这个问题的方法,
我创建了一个新类 DecimalModelBinder 来覆盖十进制字段的默认模型绑定。代码如下。在这里我尝试转换十进制值,如果转换失败,我用逗号替换所有句号并尝试再次转换。如果第二次转换尝试失败,我将所有逗号替换为句号并重试。
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState {Value = valueResult};
object actualValue = null;
try
{
// Try to convert the actual number that was recieved.
actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
}
catch
{
try
{
// Replace any . with , and try to convert.
actualValue = Convert.ToDecimal(valueResult.AttemptedValue.Replace('.',','), CultureInfo.CurrentCulture);
}
catch
{
try
{
// Replace any , with . and try to convert.
actualValue = Convert.ToDecimal(valueResult.AttemptedValue.Replace(',', '.'), CultureInfo.CurrentCulture);
}
catch (Exception ex)
{
modelState.Errors.Add(ex);
}
}
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
您必须在 Global.asx 文件中添加 DecimalModelBinder
protected void Application_Start()
{
RouteTable.Routes.MapHubs();
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
// All other code.
}