在ActionFilterAttribute期间绑定

时间:2013-02-27 16:00:46

标签: c# asp.net-mvc model-binding

努力弄清楚为什么我在这里从BindModel返回null。我有一个扩展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);

此时datanull

编辑:我回过头来认识ModelState是空的(因此导致null),因为该方法没有正常传递的模型(因此我在这种情况下具有约束力,拿起来。)

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

如何为我拥有的类型生成ModelState,并将其传递给活页夹?我试图避免将模型添加为输入参数,因为它会导致问题,但看起来我可能不得不对这些问题进行排序,如果这仍然是一个问题。

感谢。

Edit2:我在这里使用ActionFilterAttribute修改在某些情况下作为响应发送的模型,在其他情况下,它接受在缓存中更新的模型。在这种情况下,我需要绑定它。

1 个答案:

答案 0 :(得分:2)

您应该在modelbinder中进行模型绑定。不是ActionFilter。 ActionFilters用于拦截和修改请求和响应。所以,像这样清理你的ActionResult。

public ActionResult Foo(FooViewModel model)
{
    return PartialView(model);
}

然后创建一个自定义模型绑定器。

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());