문제

I am saving some values in session as below.

List<MyEntity> MyVariable = <some values here>;
System.Web.HttpContext.Current.Session["MySession"] = MyVariable;

When I try to print MySession variable in Immediate Window then it displays following:

Count = 2
    [0]: {MyProject.Model.MyEntity}
    [1]: {MyProject.Model.MyEntity}

How do I print the values which are inside these indexes 0 and 1? I tried the following but it didn't work as it shows error "Cannot apply indexing with [] to an expression of type 'object'":

System.Web.HttpContext.Current.Session["MySession"][0];
도움이 되었습니까?

해결책

You have to cast your value to the type you assigned, and apply the index on that :

((List<MyEntity>)System.Web.HttpContext.Current.Session["MySession"])[0];

The Session only hold the generic type Object for all values, you have to cast them to the correct type each time you access it. To avoid casting at multiple places, you can create a wrapper class around Session, as seen in this answer.

다른 팁

You have to cast the session object to list, here is an example :

((List<MyEntity>)System.Web.HttpContext.Current.Session["MySession"])[0]

You could try this code:

using System.Web;

List<MyEntity> list = (List<MyEntity>)HttpContext.Current.Session["MySession"];

if (list != null)
{
    foreach (MyEntity item in list)
    {
        Response.Write(item.ToString());  // <-- you may want to override ToString to display the content
    }
}

You need to cast your session object, before you can access it as a list, because you can store all kind of objects in the session and by default an object has no indexer. Thence the error message.

After that you still somehow need to implement a way to display the content of the items. You could override the ToString method of your MyEntity class to do so.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top