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

时间:2013-12-24 10:38:38

标签: 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:
                       ...
            }
        }

Request_Handler代码:

public class Request_HandlerController : Controller
    {
        public ActionResult Quran_Loading(List<thing> thin)
        {...}
    }

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

4 个答案:

答案 0 :(得分:5)

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

您可以使用以下三个选项之一ViewDataViewBagTempData将数据从控制器传递到View或其他控制器

您可以在此处查看this参考,了解有关这三个选项之间差异的更多信息。

[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:
                   ...
        }
    }

请求处理程序

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

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

答案 1 :(得分:3)

看看TempData,我认为它应该可以解决您的问题。 RedirectToAction是带有302代码的HTTP请求,并在标题中设置新位置。

ASP.NET MVC - TempData - Good or bad practice

答案 2 :(得分:3)

    [HttpPost]
    public ActionResult Admin_Mgmt(List<thing> things, int Action_Code)
    {
        switch (Action_Code)
        {
            case 1: 
                {   //redirecting requesting to another controller 
                    TempData["Things"]=things; //transferring list into tempdata 
                    return RedirectToAction("Quran_Loading", "Request_Handler",things);
                }
           default:
                   ...
        }
    }


public class Request_HandlerController : Controller
{
    public ActionResult Quran_Loading()
    {
        List<thing> things=TempData["Things"] as  List<thing>;
     }
}

TempData的

tempdata的生命周期非常短暂。重定向到另一个视图时使用的最佳方案。这背后的原因是重定向会终止当前请求并将HTTP状态代码302对象发送到服务器,并且还会创建新请求。

答案 3 :(得分:2)

TempData在使用RedirectToAction 将被清除,您应该编码如下:

<强>控制器:

TempData["things"] = (List<thing>)things;

查看:

@if(List<thing>)TempData["things"] != null)
{
  <tr>
    <td>
      <ul>
        foreach(var item in (List<thing>)TempData["things"])
        {
          <li><b>@item.PropertyName</b></li>
        }
      </ul>
    </td>
  </tr>
}