© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y 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();
var myListJson = TempData["MyList"].ToString();
I get a "cannot implicitly convert error". There should be a way to get back the list right, guys?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

How do i pass data from one form to another?
C#CC# / help
4y ago
How to pass variable from one View to another View in link?
C#CC# / help
3y ago