C
C#3mo ago
Gipper

How to pass List<string> from one action to another using TempData

From what I saw on the internet I should do:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Newtonsoft.Json;

public class MyController : Controller
{
public IActionResult FirstAction()
{
List<string> myList = new List<string> { "Item1", "Item2", "Item3" };
TempData["MyList"] = JsonConvert.SerializeObject(myList);

return RedirectToAction("SecondAction");
}

public IActionResult SecondAction()
{
List<string> myList = new List<string>();

if (TempData.ContainsKey("MyList"))
{
var myListJson = TempData["MyList"].ToString();
myList = JsonConvert.DeserializeObject<List<string>>(myListJson);
}

ViewBag.MyList = myList;
return View();
}
}
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Newtonsoft.Json;

public class MyController : Controller
{
public IActionResult FirstAction()
{
List<string> myList = new List<string> { "Item1", "Item2", "Item3" };
TempData["MyList"] = JsonConvert.SerializeObject(myList);

return RedirectToAction("SecondAction");
}

public IActionResult SecondAction()
{
List<string> myList = new List<string>();

if (TempData.ContainsKey("MyList"))
{
var myListJson = TempData["MyList"].ToString();
myList = JsonConvert.DeserializeObject<List<string>>(myListJson);
}

ViewBag.MyList = myList;
return View();
}
}
But that seems wrong because whenever I try to do the line: var myListJson = TempData["MyList"].ToString(); I get a "cannot implicitly convert error". There should be a way to get back the list right, guys?
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server