4

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.

3 Answers 3

12

Try this:

Supply sup =  Supplies.GetSupply(supplyItemID); 
var cartObjects =  (Session["CartObjects"] as List<Supply>) ?? new List<Supply>();
cartObjects.Add(sup);
Session["CartObjects"] = cartObjects;
Sign up to request clarification or add additional context in comments.

Comments

7

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

Session["CartObjects"] = sup;

1 Comment

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

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 >

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.