ASP.NET MVC 3自定义操作过滤器 - 如何传入模型添加到TempData的? [英] ASP.NET MVC 3 Custom Action Filter - How to add incoming model to TempData?

查看:297
本文介绍了ASP.NET MVC 3自定义操作过滤器 - 如何传入模型添加到TempData的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个自定义操作过滤器,它抓住了进入的模式从过滤器断章取义,把它添加到TempData的,然后执行其他的东西。

我的操作方法是这样的:

  [HttpPost]
[MyCustomAttribute]
公众的ActionResult创建(MyViewModel模型)
{
   //剪断为了简洁...
}

现在,我想在模式添加到的TempData 之后的模型结合位已经踢和转化的形式收藏价值为 MyViewModel

我该怎么办呢?

 公共覆盖无效OnActionExecuting(ActionExecutingContext filterContext)
{
   如果(!filterContext.Controller.ViewData.ModelState.IsValid)
      返回;   VAR模型= filterContext ????。 //我如何得到的模型界的对象?
   filterContext.TempData.Add(someKey,模型);
}


解决方案

明白了 - 希望这是做它的正确方法:

 公共覆盖无效OnActionExecuting(ActionExecutingContext filterContext)
{
   如果(!filterContext.Controller.ViewData.ModelState.IsValid)
      返回;   VAR模型= filterContext.ActionParameters.SingleOrDefault(AP => ap.Key ==模式)值。
   如果(型号!= NULL)
   {
      //找到该模型 - 它添加到TempData的
      filterContext.Controller.TempData.Add(TempDataKey,模型);
   }
}

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

这篇关于ASP.NET MVC 3自定义操作过滤器 - 如何传入模型添加到TempData的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆