具有全局数字格式的ASP.NET MVC模型绑定器

Nic*_*eve 9 asp.net-mvc localization model number-formatting custom-model-binder

当我的应用程序在使用不同数字格式的小数(例如1.2 = 1,2)的国家/地区使用时,默认模型绑定器会返回类型为double的属性的错误.网站的文化是在我的BaseController中有条件地设置的.

我已经尝试添加自定义模型绑定器并覆盖bindModel函数但我无法看到如何解决错误,因为Culture已经设置回默认的en-GB.

所以我尝试在我的BaseController中添加一个动作过滤器来设置Culture,但不幸的是bindModel似乎在我的动作过滤器之前被触发了.

我怎么能绕过这个?要么让文化不重置自己,要么在bindModel启动之前将其设置回来?

模型进入无效的控制器:

public ActionResult Save(MyModel myModel)
{
    if (ModelState.IsValid)
    {
        // Save my model
    }
    else
    {
       // Raise error
    }
}
Run Code Online (Sandbox Code Playgroud)

筛选文化设置:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    CultureInfo culture = createCulture(filterContext);

    if (culture != null)
    {
         Thread.CurrentThread.CurrentCulture = culture;
         Thread.CurrentThread.CurrentUICulture = culture;
    }

    base.OnActionExecuting(filterContext);
}
Run Code Online (Sandbox Code Playgroud)

自定义模型粘合剂:

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;
   }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*usa -1

请看一下这篇文章,但简而言之,如果您可以尝试一下:

public ActionResult Create(FormCollection values)
{
    Recipe recipe = new Recipe();
    recipe.Name = values["Name"];      

    // ...

    return View();
}
Run Code Online (Sandbox Code Playgroud)

...或者这个,如果你有一个模型:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Recipe newRecipe)
{            
    // ...

    return View();
}
Run Code Online (Sandbox Code Playgroud)

该文章提供了完整的参考资料和其他实现此目的的方法。我用这两个,到目前为止它们对我来说已经足够了。