How to pass List in Redirecttoaction

假装没事ソ 提交于 2019-11-27 15:32:11

You cannot pass a collection of complex objects in urls when redirecting.

One possibility would be to use TempData:

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

and then inside the Question action:

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

This is probably not even active anymore, but I'll leave how I did it here to maybe help someone else.

I solved this using a simple Redirect instead of a RedirectToAction:

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

Then, on your other method:

public ActionResult Action(List<int> parameterList){}

RedirectToAction method Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action.

You should either keep the data in a temporary storage like TempData / Session . TempData uses Session as the backing storage.

If you want to keep it real Stateless, you should pass an id in the query string and Fetch the List of items in your GET Action. Truly Stateless.

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

and in your GET method

public ActionResult Question(string email,int id)
{

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

Assuming repositary.GetTabelFieldsFromID returns a List of TabelFields from the Id

The way that I solved this problem was to serialize the list to a JSON object using the JsonConvert method from the Newtonsoft.Json nuget package. Then the serialized list can be passed as a parameter and then deserialized again to re-create the original list.

So in your SelectQuestion method you would use this code:

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

And in your Question method, you would use this code to deserialize the object.

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

Important, this adds the model as a query string parameter to your url, so only do this with really simple small objects, otherwise your url will be too long.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!