The default model binder is returning errors for properties that are of type double when my application is being used in countries that use different number formatting for decimals (e.g. 1.2 = 1,2). The culture of the site is set conditionally in my BaseController.
I have tried adding a custom model binder and overriding the bindModel function but I can't see how to get around the error in there as the Culture has already been set back to the default of en-GB.
So I tried adding an action filter to my BaseController that sets the Culture there but unfortunately bindModel seems to get fired before my action filter.
How can I get around this? Either by getting the Culture to not reset itself or set it back before bindModel kicks in?
Controller where model comes in invalid:
public ActionResult Save(MyModel myModel)
{
if (ModelState.IsValid)
{
// Save my model
}
else
{
// Raise error
}
}
Filter where Culture is set:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
CultureInfo culture = createCulture(filterContext);
if (culture != null)
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
base.OnActionExecuting(filterContext);
}
Custom Model Binder:
public class InternationalDoubleModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueResult != null)
{
if (bindingContext.ModelType == typeof(double) || bindingContext.ModelType == typeof(Nullable<double>))
{
double doubleAttempt;
doubleAttempt = Convert.ToDouble(valueResult.AttemptedValue);
return doubleAttempt;
}
}
return null;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…