How to get value from TempData with Listobject?

2

Follow the code below:

List<object> list = new List<object>
{
    "abc",      // string
    1,          // int
    true        // bool
};

TempData["ID"] = list;

The following code can not fetch value:

var data = TempData["ID"];

var test1 = data[0];  //<---- Problema: Não é possível aplicar a indexação com [] a uma expressão do tipo "object"

Is there a solution or is there an easier way?

    
asked by anonymous 21.05.2017 / 05:21

1 answer

2

Since the value of each TempData is of type object there is really no indexer for it. You would have to cast cast to List<object> to actually have a list ready and access its elements.

using System.Collections.Generic;

public class Program {
    public static void Main() {
        var list = new List<object> {
            "abc",      // string
            1,          // int
            true        // bool
        };
        var TempData = new Dictionary<string, object>(); //só pra poder testar aqui
        TempData["ID"] = list;
        var data = TempData["ID"];
        var test1 = ((List<object>)data)[0];
    }
}

See running on .NET Fiddle . And at Coding Ground . Also I put it in GitHub for future reference .

But I will say that this seems to be a beautiful gambiarra. Almost every time someone creates a list with objects , especially if it has few elements, it's probably doing something wrong. If you need this you probably need a class or tuple and not a list. This becomes clearer with the comments used.

I'm already in doubt whether to use TempData .

    
21.05.2017 / 06:36