ASP.net, agregando objetos a una variable de sesión

I'm trying to add an object(s) to a session variable across postbacks. My code looks similar to the following.

  Supply sup =  Supplies.GetSupply(supplyItemID);

  Session["CartObjects"] += sup;

Now, the compiler throws an error saying that the "+=" operator cannot be used on type 'object' and 'Supply'. Do I need to implement an interface on my Supply object that allows it to be added? Is this possible or am I thinking about this in the completely wrong way.

preguntado el 08 de noviembre de 11 a las 19:11

3 Respuestas

Prueba esto:

Supply sup =  Supplies.GetSupply(supplyItemID); 
var cartObjects =  (Session["CartObjects"] as List<Supply>) ?? new List<Supply>();
cartObjects.Add(sup);
Session["CartObjects"] = cartObjects;

respondido 08 nov., 11:23

unless you are trying to create some sort of array the syntax is just

Session["CartObjects"] = sup;

respondido 09 nov., 11:00

Yes, actually a list/array of objects. Something along the lines of ((List<Supply>)Session["CartObjects"]).Add(sup); - John Czajka

No You dont need ,just Create a List of Supply and Save it in session

var supplyList = new List<Supply >();
Supply sup =  Supplies.GetSupply(supplyItemID);
supplyList.Add(sup);
Session["CartObjects"] =supplyList;

and 
and cast it as supply List
var list = Session["CartObjects"] as List<Supply >

respondido 09 nov., 11:00

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.