eriksv88
eriksv88

Reputation: 3528

PHP to C#.NET/ASP.NET

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"];

Upvotes: 2

Views: 201

Answers (3)

Charlie
Charlie

Reputation: 10307

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;
}

Upvotes: 1

synhershko
synhershko

Reputation: 4492

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.

Upvotes: 0

Palantir
Palantir

Reputation: 24182

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 :)

Upvotes: 0

Related Questions