How to get Tempdata value with List<Object>?

Asked

Viewed 698 times

2

Follows code:

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

TempData["ID"] = list;

The following code cannot get 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"

Some solution or other easier way ?

1 answer

2


As the value of each TempData is the type object there really is no indexer for it. It would have to make a cast for List<object> to actually have a list in hand and then 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];
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

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

I’m already wondering if I should use the TempData.

  • Because the idea is to send Actionresult values to another Actionresult without using parameter. Then it would be like: Tempdata ?

  • 1

    Some cases do, but some cases are better Viewmodel, and it seems to be your case, despite having posted a very abstract example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.