【发布时间】:2010-11-18 14:21:11
【问题描述】:
是否可以在 Asp.net C# 中将列表存储到会话变量中?
【问题讨论】:
-
请查看标签。他已经明确提到了 C# asp.net
是否可以在 Asp.net C# 中将列表存储到会话变量中?
【问题讨论】:
是的,您可以存储任何对象(我假设您正在使用具有默认设置的 ASP.NET,即进程内会话状态):
Session["test"] = myList;
您应该将其转换回原始类型以供使用:
var list = (List<int>)Session["test"];
// list.Add(something);
正如 Richard 所指出的,如果您使用需要可序列化对象的其他会话状态模式(例如 SQL Server),则应格外小心。
【讨论】:
T 是可序列化的,则List<T> 是可序列化的。 2.默认会话状态模式为in-proc。
CType(Session("test"), List(of int32))
是的。你是为哪个平台写的? ASP.NET C#?
List<string> myList = new List<string>();
Session["var"] = myList;
然后,检索:
myList = (List<string>)Session["var"];
【讨论】:
我在Page范围之外的类文件中发现,上述方式(我一直使用的)不起作用。
我在这个“上下文”中找到了一种解决方法,如下所示:
HttpContext.Current.Session.Add("currentUser", appUser);
和
(AppUser) HttpContext.Current.Session["currentUser"]
否则,当我将对象指向会话对象时,编译器会期待一个字符串。
【讨论】:
'HttpContextBase' does not contain a definition for 'Current' and no extension method 'Current' accepting a first argument of type 'HttpContextBase' could be found (are you missing a using directive or an assembly reference?
试试这个..
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
【讨论】:
YourListType ListName = (List<YourListType>)Session["SessionName"];
【讨论】:
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"});
现在将 obj 分配给会话
Session["Product"]=obj;
用于检索会话。
ProductList objLst = (ProductList)Session["Product"];
【讨论】: