MarkCo
MarkCo

Reputation: 1212

TempData with same key with multiple values asp.net core mvc

I was reading up on temp data and wanted to know if you can use tempdata with two separate keys and add more than one value to those. I.e.

TempData["Id"] = "1";

TempData["Name"] = "Bob";

then we have another set of values to add in the tempdata:

TempData["Id"] = "2";
TempData["Name"] = "Jill";

Using those in an action method:

public ActionResult Index()
{

    TempData["Id"] = 1;
    
    TempData["Name"] = "Bob";

    TempData["Id"] = 2;
    
    TempData["Name"] = "Jill";
}

then accessing that in another action method without having it to override the values of the keys and just give the last set of id and name:

public ActionResult About()
{

    int id;
    string name;

    if (TempData.ContainsKey("Id") && TempData.ContainsKey("Name"))
    {
         id = Convert.ToInt32(TempData["Id"]);
         name = TempData["Name"].ToString();
    }

}

Is there a way to display both Id's for Bob and Jill and both of their names when accessing it in the About() action method without just only getting 2 for ID and Jill for name, returned?

Upvotes: 0

Views: 1983

Answers (1)

Serge
Serge

Reputation: 43870

This code was tested using VS 2019 and Newtonsoft.Json nuget package

you can keep a complex data in tempdata this way

public class IdName
{
 public int Id {get;set;}
public string Name {get; set;}
}

you can use it likes this


var idNames = new List<IdName> { 
new IdName { Name = "Bob", Id = 1 }, 
new IdName { Name = "Jill", Id = 2 } 
};
TempData["IdNames"] = JsonConvert.SerializeObject(idNames);

and your action

public ActionResult About()
{

if ( TempData.ContainsKey("IdNames") ) 
{
  List<IdName> IdNames =  JsonConvert.DeserializeObject<List<IdName>>( TempData["IdNames"].ToString());

    foreach( item in IdNames)
    {

        var id= item.Id;
        var name= item.Name

         // your code
    }
}

Upvotes: 1

Related Questions