ASP.NET MVC 3自定义操作过滤器 - 如何将传入模型添加到TempData?

RPM*_*984 3 c# tempdata model-binding custom-action-filter asp.net-mvc-3

我正在尝试构建一个自定义动作过滤器,它从过滤器上下文中获取传入模型,将其添加到tempdata,然后执行"其他内容".

我的动作方法如下所示:

[HttpPost]
[MyCustomAttribute]
public ActionResult Create(MyViewModel model)
{
   // snip for brevity...
}
Run Code Online (Sandbox Code Playgroud)

现在,我要添加modelTempData,模型结合已经踢并转化形式收藏价值成MyViewModel.

我怎么做?

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   if (!filterContext.Controller.ViewData.ModelState.IsValid)
      return;

   var model = filterContext.????; // how do i get the model-bounded object?
   filterContext.TempData.Add(someKey, model);
}
Run Code Online (Sandbox Code Playgroud)

RPM*_*984 5

得到它 - 希望这是正确的方法:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   if (!filterContext.Controller.ViewData.ModelState.IsValid)
      return;

   var model = filterContext.ActionParameters.SingleOrDefault(ap => ap.Key == "model").Value;
   if (model != null)
   {
      // Found the model - add it to tempdata
      filterContext.Controller.TempData.Add(TempDataKey, model);
   }
}
Run Code Online (Sandbox Code Playgroud)