如何将对象列表从一个控制器传递到另一个控制器?

Baq*_*qvi 1 c# asp.net-mvc

我需要将对象列表从一个控制器传递到另一个控制器.我已经阅读了类似问题的答案,但没有什么可以帮助我.这是第一个控制器的代码:

[HttpPost]
        public ActionResult Admin_Mgmt(List<thing> things, int Action_Code)
        {
            switch (Action_Code)
            {
                case 1: 
                    {   //redirecting requesting to another controller 
                        return RedirectToAction("Quran_Loading", "Request_Handler",things);
                    }
               default:
                       ...
            }
        }
Run Code Online (Sandbox Code Playgroud)

Request_Handler代码:

public class Request_HandlerController : Controller
    {
        public ActionResult Quran_Loading(List<thing> thin)
        {...}
    }
Run Code Online (Sandbox Code Playgroud)

但问题是Quran_Loading方法中的列表为null.任何的想法 ?

Moh*_*lah 5

在操作中无法将List从控制器传递到另一个,因为RedirectToAction是您无法将列表传递给的HTTP请求.

您可以使用以下三个选项之一ViewData,ViewBagTempData从控制器传递数据查看或其他控制器

您可以在此处查看参考,以获取有关这三个选项之间差异的更多信息.

[HttpPost]
public ActionResult Admin_Mgmt(List<thing> things, int Action_Code)
 {
      switch (Action_Code)
      {
          case 1: 
             {   
                    TempData["Things"] = things; 
                    // OR 
                    ViewBag.Things = things;
                    // OR 
                    ViewData["Things"] = things;

                    //redirecting requesting to another controller 
                    return RedirectToAction("Quran_Loading", "Request_Handler");
             }
           default:
                   ...
        }
    }
Run Code Online (Sandbox Code Playgroud)

请求处理程序

public class Request_HandlerController : Controller
{
    public ActionResult Quran_Loading()
    {
          List<thing> things = (List<thing>)TempData["Things"];
          // Do some code with things here
    }
}
Run Code Online (Sandbox Code Playgroud)

检查此代码并告诉我是否有任何问题

  • 使用 RedirectToAction 时,只有 TempData 有效,ViewBag 和 ViewData 无效,因为它们将被清除。 (2认同)