如何在RedirectToAction中通过List传递数据

15

我想从RedirectToAction方法中传递多个参数,该怎么做?

我的一个Action方法

 [HttpPost, ActionName("SelectQuestion")]
    public ActionResult SelectQuestion(string email,List<QuestionClass.Tabelfields> model)
    {

        List<QuestionClass.Tabelfields> fadd = new List<QuestionClass.Tabelfields>();
        for (int i = 0; i < model.Count; i++)
        {
            if (model[i].SelectedCheckbox == true)
            {
                List<QuestionClass.Tabelfields> f = new List<QuestionClass.Tabelfields>();
                fadd.Add(model[i]);
            }
        }

        return RedirectToAction("Question", new { email = email, model = fadd.ToList() });
    }

我的另一个操作方法

    [HttpGet]
    public ActionResult Question(string email,List<QuestionClass.Tabelfields> model)
    {
    }

我没有在model中获取到值。

4个回答

25

在重定向时,无法通过URL传递复杂对象的集合。

一个可能的解决方案是使用TempData:

TempData["list"] = fadd.ToList();
return RedirectToAction("Question", new { email = email});

然后在“Question”操作内部:

var model = TempData["list"] as List<QuestionClass.Tablefields>;

实际上我需要在URL中获取电子邮件ID和模型,我该如何获取它? - Ajay

5
我解决这个问题的方式是使用Newtonsoft.Json NuGet包中的JsonConvert方法将列表序列化为JSON对象。然后,可以将序列化后的列表作为参数传递,然后反序列化以重新创建原始列表。
因此,在您的SelectQuestion方法中,您将使用以下代码:
return RedirectToAction("Question", 
    new { 
        email = email, 
        serializedModel = JsonConvert.SerializeObject(fadd.ToList()) 
    });

在您的Question方法中,您将使用以下代码来反序列化对象。
[HttpGet]
public ActionResult Question(string email, string serializedModel)
{
    // Deserialize your model back to a list again here.
    List<QuestionClass.Tabelfields> model = JsonConvert.DeserializeObject<List<QuestionClass.Tabelfields>>(serializedModel);
}

重要提示,这将模型添加为查询字符串参数到您的URL中,所以只适用于非常简单小的对象,否则您的URL会变得太长。


到目前为止,这是最不糟糕的解决方案。 - matthy
这个对我来说是最直接的。谢谢! - CusterN
不仅要让它工作,还要让它优雅。您需要进行序列化以添加复杂类型,例如将列表添加到TempData中。 - Zi Cold

4

这可能已经不再使用了,但我会把我是如何做到的留在这里,希望能帮助其他人。

我使用简单的重定向而不是RedirectToAction解决了这个问题:

List<int> myList = myListofItems;
var list = HttpUtility.ParseQueryString("");
myList.ForEach(x => list.Add("parameterList", x.ToString()));
return Redirect("/MyPath?" + list);

然后,在您的另一个方法中:
public ActionResult Action(List<int> parameterList){}

3

RedirectToAction方法会向浏览器返回一个HTTP 302响应,从而导致浏览器发出到指定操作的GET请求。

你应该将数据保存在临时存储中,如TempData / Session。 TempData使用Session作为后备存储。

如果你想保持真正的无状态,你应该在查询字符串中传递一个id,并在您的GET操作中获取项目列表。确实是无状态的。

return RedirectToAction("Question", new { email = email,id=model.ID });

在你的GET方法中

public ActionResult Question(string email,int id)
{

   List<QuestionClass.Tabelfields> fadd=repositary.GetTabelFieldsFromID(id);
    //Do whatever with this
   return View();
}

假设 repositary.GetTabelFieldsFromID 返回一个 TabelFields 列表,其中包含该 Id 对应的字段。

有没有这样的选项 return RedirectToAction("Question", new { email = email, model = fadd.ToList() });我没有得到我想要的答案。我想传递电子邮件和列表。 谢谢 - Ajay
1
@Ajay:就像我告诉你的那样,这是一个重定向(一个新的HTTP请求,你不能直接传递这样一个复杂的对象)。你需要尝试以上任何一种方法(临时存储/重新查询)。请记住,HTTP是无状态的。 - Shyju

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接