PHP for C # .NET / ASP.NET

How can I write this in C #? Can you use a dictionary for 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"];

      

+2


source to share


3 answers


There are many ways to do this, but here's one easy way. (This code must be in your page code because it requires the Page.Session property)

For starters, you might want the Product object 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 the 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;
}

      

+1


source


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

First, you need to define a class to store your shopping cart items, let's call it CartItem for example. Then you will instantiate a CartItem object, set its fields to column values, and finally, you will add the cart item to the list that will be stored in the Session object.



Good luck :)

0


source


There are many ways, depending on your planned storage and access methods and the size of the data structure required.

For example, one way would be to create an object with member_id, price and number variables, and also store it in an array and then in Cache / Session.

0


source







All Articles