【问题标题】:ASP.NET MVC 3 Custom Action Filter - How to add incoming model to TempData?ASP.NET MVC 3 自定义操作过滤器 - 如何将传入模型添加到 TempData?
【发布时间】:2011-04-11 04:06:28
【问题描述】:

我正在尝试构建一个自定义操作过滤器,该过滤器从过滤器上下文中获取传入模型,将其添加到 tempdata,然后执行“其他操作”。

我的操作方法如下所示:

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

现在,我想将 model 添加到 TempData 模型绑定开始并将表单值集合转换为 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);
}

【问题讨论】:

  • 请注意 Tempdata 在会话中存储东西..

标签: c# asp.net-mvc-3 model-binding tempdata custom-action-filter


【解决方案1】:

知道了 - 希望这是正确的做法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多