9

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

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

所以我尝试向我的 BaseController 添加一个动作过滤器,在那里设置文化,但不幸的是 bindModel 似乎在我的动作过滤器之前被触发了。

我怎样才能解决这个问题?通过让 Culture 不重置自身或在 bindModel 启动之前将其设置回来?

模型无效的控制器:

public ActionResult Save(MyModel myModel)
{
    if (ModelState.IsValid)
    {
        // Save my model
    }
    else
    {
       // Raise error
    }
}

过滤设置文化的地方:

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

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

    base.OnActionExecuting(filterContext);
}

自定义模型绑定器:

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;
   }
}
4

2 回答 2

3

您希望您的应用程序使用单一文化,对吗?如果是这样,您可以使用 web.config 的全球化标记来执行此操作。

<configuration>
    <system.web>
        <globalization
           enableClientBasedCulture="true"        
           culture="en-GB"
           uiCulture="en-GB"/>
    </system.web>
</configuration>

然后您可以忘记那些自定义模型绑定器并使用默认值。

更新:好的,这是一个多语言应用程序。你如何获得你想要的文化?你可以在 MvcApplication 类上调用 createCulture 吗?你可以这样做:

public class MvcApplication : HttpApplication
{
    //...
    public void Application_OnBeginRequest(object sender, EventArgs e)
    {
        CultureInfo culture = GetCulture();
        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;
    }
    //...
}

此方法在模型绑定之前调用,因此,您不需要自定义模型绑定器。我希望这个对你有用 :)

于 2011-02-21T10:59:07.687 回答
-1

看看这篇文章,但简而言之,如果你可以试试这个:

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

    // ...

    return View();
}

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

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

    return View();
}

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

于 2011-02-19T14:57:59.787 回答