2013-02-27 51 views
0

努力弄清楚爲什麼我在這裏從BindModel返回null。我有一個擴展ActionFilterAttribute屬性...在ActionFilterAttribute中綁定

public class MyCachedAttribute : ActionFilterAttribute 
{ 
    private IModelBinder binder = new DefaultModelBinder(); 
    private Type model; 

    public MyCachedAttribute(Type model) 
    { 
    this.model = model; 
    } 

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
    ModelBindingContext bindingContext = new ModelBindingContext() 
    { 
     ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, model), 
     ModelName = model.Name, 
     ModelState = filterContext.Controller.ViewData.ModelState, 
     ValueProvider = filterContext.Controller.ValueProvider 
    }; 

    object data = binder.BindModel(filterContext.Controller.ControllerContext, bindingContext); 

data在這一點上是null

編輯:我已經回到這個,並認識到ModelState是空的(因此導致null),因爲該方法沒有正常傳入的模型(因此,爲什麼我在這種情況下綁定,撿起它)。

[MyCached(typeof(FooViewModel))] 
    public ActionResult Foo() 
    { 
    return PartialView(new FooViewModel()); 
    } 

我該如何爲我有的類型生成ModelState,並將它傳遞給活頁夾?我試圖避免添加模型作爲輸入參數,因爲它會導致問題,但它看起來像我可能不得不排序這些問題,而如果這仍然是一個問題。

謝謝。

EDIT2:我使用的是ActionFilterAttribute這裏修改發送,在某些情況下,響應模型,而在其他情況下,它接受一個模型,在高速緩存中進行更新。在這種情況下,我需要綁定它。

+0

什麼你想達到多少?它看起來像你想創建一個自定義模型綁定器,應該從'DefaultModelBinder'派生而不是創建'ActionFilterAttribute'。 – 2013-02-27 17:18:04

+0

當使用此屬性併發送POST命令時,我稍後使用模型將其存儲在緩存中。我已經刪除了代碼,只是綁定過程。 – Tim 2013-02-27 17:50:18

+0

如果你想做緩存,爲什麼不使用'OutputCacheAttribute'? – 2013-02-27 17:57:53

回答

2

您應該在modelbinder中進行模型綁定。不是ActionFilter。 ActionFilters用於攔截和修改請求和響應。所以,像這樣清理你的ActionResult。

​​

然後創建一個自定義模型聯編程序。

public class CachedModelBinder : DefaultModelBinder { 

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { 
    object data = base.BindModel(controllerContext, bindingContext); 
    // data is not null anymore. You can do your custom stuff now, then return the model 
    return data; 
} 

,並在Application_Start()註冊在你global.asax.cs

ModelBinders.Binders.Add(typeof(FooViewModel), new CachedModelBinder()); 
+0

我想修改請求和響應,所以這是一個合適的屬性。該屬性應該修改「GET」上的模型響應,並接受「POST」上的更新模型。 – Tim 2013-02-28 09:43:49

+0

當你嘗試使用object data = binder.BindModel(filterContext.Controller.ControllerContext,bindingContext)時,你做了很多工作並得到null。在MyCachedAttribute中。雖然你可以只是對象data = base.BindModel(controllerContext,bindingContext);在我給你的例子中。現在,再次告訴我你是在正確的地方做的。我已經更新我的示例,只是綁定你想綁定的'對象數據'。 – 2013-02-28 16:02:12