问题
ASP.NET: Is it possible to keep complex object such as List<object> is the session? If yes, how to do so? I'm trying to keep a list in the session, but I'm being told that I cannot convert that List to a string.
EDIT
[Serializable]
public class Client
{
public string ClientType { get; set; }
public string ClientName { get; set; }
public string SubClientName { get; set; }
public string Project { get; set; }
public string Service { get; set; }
public string Activity { get; set; }
}
List<Client> ListOfClients;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ListOfClients = new List<Client> { new Client()};
Session["ListOfClients"] = ListOfClients;//This is where the error occurs
//Cannot convert List<Client> to string...
}
}
There are many operations to execute, but the idea is to keep whatever is in the list of clients in the session.
Thanks for helping.
回答1:
Yes, you can store any serializable object into a session variable. For example:
List<string> list;
Session["list"] = list;
Then to return the value:
List<string> list = (List<string>)Session["list"];
回答2:
You can store anything in the session object as long as session state is in InProc mode.
Otherwise what you store has to be serialisable.
Note that the type of what you store is object, so you cast the reference that you get back:
ListOfClients = Session["ListOfClients"] as List<Client>;
回答3:
Since you wrote in a comment that the error happens when compiling as opposed to at runtime, I suspect that you have some other object called Session that masks the Page.Session.
Try to hover your mouse over the Session text in Visual Studio. The tooltip should show you that Session is of type
System.Web.SessionState.HttpSessionState
If it's showing something else, you need to search both your markup (.aspx file) and code behind file to see if you have declared something else with the name/id Session and then change that name/id.
来源:https://stackoverflow.com/questions/11955094/asp-net-is-it-possible-to-keep-complex-object-such-as-list-is-the-session