2010-02-22 50 views
2

原因似乎很簡單:模型結合(並且因此驗證)的最早ActionFilter方法(OnActionExecuting)被執行之前發生,因此改變UICulture上驗證沒有影響消息。數據註釋驗證消息未本地化

是否有早期的積分點(除了IHttpModule)我可以在這裏使用?

我寧願一個屬性爲基礎的方法,因爲功能並不適用於所有的控制器/行動,以便IHttpModules聽起來不像是個好主意(排除過濾列表和這樣)

回答

1

好,我能想到的最簡單的「基於屬性」的解決方案是一種破解...

授權過濾器在模型聯編程序執行其工作之前運行。所以如果你寫一個假的AuthorizeAttribute,你可以在那裏設置文化。

public class SetCultureAttribute : AuthorizeAttribute { 
    protected override bool AuthorizeCore(HttpContextBase httpContext) { 
     //set the culture here 
     return true; //so the action will get invoked 
    } 
} 
//and your action 
[SetCulture] 
public ActionResult Foo(SomeModel m) { 
    return View(); 
} 
+0

好主意,我忘了'AuthorizeAttribute'。如果有更優雅的解決方案,我會留下問題,但您的答案看起來不錯:) –

0

想到解決這個問題的另一種解決方案。
我相信這比the other solution更優雅,它是基於屬性的(儘管這取決於你想如何將這個活頁夾粘貼到你的模型上)。

您可以創建自己的模型綁定器,並從DataAnnotationsModelBinder派生它。然後在告訴基類綁定模型之前設置文化。

public class CustomModelBinder : DataAnnotationsModelBinder { 
    public override object BindModel(ControllerContext controllerContext, 
     ModelBindingContext bindingContext) { 

     //set the culture 
     return base.BindModel(controllerContext, bindingContext); 
    } 
} 
//and the action 
public ActionResult Foo([ModelBinder(typeof(CustomModelBinder))]SomeModel m) { 
    return View(); 
} 

//Or if you don't want that attribute on your model in your actions 
//you can attach this binder to your model on Global.asax 
protected void Application_Start() { 
    ModelBinders.Binders.Add(typeof(SomeModel), new CustomModelBinder()); 
    RegisterRoutes(RouteTable.Routes); 
}