开发者

ASP.NET MVC 3 Custom Action Filter - How to add incoming model to TempData?

I'm trying to build a custom action filter which grabs the incoming model out of the filter context, adds it to tempdata, then does "other stuff".

My action method looks like this:

[HttpPost]
[MyCustomAttribute]
public ActionResult Create(MyViewModel model)
{
   // snip for brevity...
}

Now, i want to add the model to TempData, after the model-开发者_运维知识库binding has kicked in and transformed the form value collection into MyViewModel.

How do i do that?

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


Got it - hopefully this is the correct way of doing it:

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);
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜