2

How to write this in C #? Can you use Dictionary to this?

$count = 0;
if(count($_SESSION['goods']) > 0) {
   $count = count($_SESSION['goods']) -1; // array start on zero.
}

$_SESSION['goods'][$count]["products_id"] = $_POST["products_id"];
$_SESSION['goods'][$count]["price"] = $_POST["price"];
$_SESSION['goods'][$count]["number"] = $_POST["number"];
1
  • 5
    suggest you post your attempt... Commented Sep 9, 2009 at 11:07

3 Answers 3

1

There's lots of ways of doing this, but here's one simple way. (This code will need to be in your page code behind because it requires the Page.Session property)

To start with, you may want a Product entity to store your data:

[Serializable]
public class Product
{
  public int ProductId{get;set;}
  public int Price{get;set;}
  public int Number{get;set;}
}

Then you can store your products in session like this:

public void AddProductToSession(Product product)
{
  var products = Session["goods"] as Dictionary<int, Product>;
  if (products == null) products = new Dictionary<int, Product>();
  products.Add(product.ProductId, product);
  Session["goods"] = product;
}

public Product GetProductFromSession(int productId)
{
  Product product;
  var products = Session["goods"] as Dictionary<int, Product>;
  if (products == null || !products.TryGetValue(productId, out product))
    throw Exception(string.Format("Product {0} not in session", productId));
  return product;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I have programmed php for several years, but has now gone over to. NET. And this was one of the things I wondered at. NET:)
0

You will need to make some more work in C#.

First, you'll need to define a class to hold your shopping cart items, call it for example CartItem. Then you will instantiate a CartItem object, set its fields to the post values, and finally you will add the shopping cart item to a List, which will be held in the Session object.

Good luck :)

Comments

0

Many ways, depending on your planned store and access methods, and size of required data structure.

For example, one way would be to create an object with products_id, price and number member variables, and store it within an array, and then into Cache / Session.

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.