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

青春壹個敷衍的年華 提交于 2020-01-01 16:10:29

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/5616653/asp-net-mvc-3-custom-action-filter-how-to-add-incoming-model-to-tempdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!