C# 存储列表到会话

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1259934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:20:58  来源:igfitidea点击:

Store List to session

c#asp.netlistsession

提问by Avinash

is it possible to store list to session variable in Asp.net C# ?

是否可以在 Asp.net C# 中将列表存储到会话变量?

回答by Mehrdad Afshari

Yes, you can store any object (I assume you are using ASP.NET with default settings, which is in-process session state):

是的,您可以存储任何对象(我假设您使用具有默认设置的 ASP.NET,即进程内会话状态):

Session["test"] = myList;

You should cast it back to the original type for use:

您应该将其转换回原始类型以供使用:

var list = (List<int>)Session["test"];
// list.Add(something);

As Richard points out, you should take extra care if you are using other session state modes (e.g. SQL Server) that require objects to be serializable.

正如 Richard 指出的那样,如果您使用其他需要对象可序列化的会话状态模式(例如 SQL Server),您应该格外小心。

回答by Paul McLean

Yes. Which platform are you writing for? ASP.NET C#?

是的。你为哪个平台写作?ASP.NET C#?

List<string> myList = new List<string>();
Session["var"] = myList;

Then, to retrieve:

然后,要检索:

myList = (List<string>)Session["var"];

回答by Don-e Merson

I found in a class file outside the scope of the Page, the above way (which I always have used) didn't work.
I found a workaround in this "context" as follows:

我发现在页面范围之外的类文件中,上述方式(我一直使用)不起作用。
我在这个“上下文”中找到了一个解决方法,如下所示:

HttpContext.Current.Session.Add("currentUser", appUser);

and

(AppUser) HttpContext.Current.Session["currentUser"]

Otherwise the compiler was expecting a string when I pointed the object at the session object.

否则,当我将对象指向会话对象时,编译器需要一个字符串。

回答by Alejandro Garcia

Try this..

尝试这个..

    List<Cat> cats = new List<Cat>
    {
        new Cat(){ Name = "Sylvester", Age=8 },
        new Cat(){ Name = "Whiskers", Age=2 },
        new Cat(){ Name = "Sasha", Age=14 }
    };
    Session["data"] = cats;
    foreach (Cat c in cats)
        System.Diagnostics.Debug.WriteLine("Cats>>" + c.Name);     //DEBUGGG

回答by Marwah Abdelaal

YourListType ListName = (List<YourListType>)Session["SessionName"];

回答by Ubaid Ur Rehman

public class ProductList
{
   public string product{get;set;}
   public List<ProductList> objList{get;set;}
}

ProductList obj=new ProductList();
obj.objList=new List<ProductList>();
obj.objList.add(new ProductList{product="Football"});

now assign obj to session

现在将 obj 分配给会话

Session["Product"]=obj;

for retrieval of session.

用于检索会话。

ProductList objLst = (ProductList)Session["Product"];