gpt4 book ai didi

c# - 如何在 ASP.NET C# 中使用 session 更改替换对象的变量

转载 作者:太空宇宙 更新时间:2023-11-03 11:14:45 25 4
gpt4 key购买 nike

我想弄清楚如何通过网络浏览器更改客户的订单。客户将订购带有产品 ID(键)、产品名称、产品价格和他想要的数量的商品。 我想知道如何通过用不同数量的相同元素替换旧数量的旧元素来更改他的订单所以基本上点击选择元素并放置他希望的 2 个不同数量购买。购物车包含已购买的商品,所以我想知道如何从购物车中销毁 OrderItem 然后重新创建它。

当我的代码找到购物车中已有的键时,需要销毁它并使用新的数量(网络应用程序中的文本框)重新创建。

  protected void btnOrder_Click(object sender, EventArgs e)
{
//Check for Shoppingcart object
// Create first if not there
if (Session["cart"] == null)
Session["cart"] = new ShoppingCart();
int quantity = 0;

// make sure there is text
if (txtQuantity.Text.Trim().Length != 0)
{
quantity = int.Parse(txtQuantity.Text);

if (((ShoppingCart)Session["cart"]).
keyExists(int.Parse(productID.Text)))
{
//Here I should Destroy the current item that exists and replace with new one

}
else // This is a new item
{
// Make the item
OrderItem item = new OrderItem(
int.Parse(productID.Text), productName.Text,
double.Parse(productPrice.Text),
int.Parse(txtQuantity.Text));
// add to cart
((ShoppingCart)Session["cart"]).addToCart(item);

}
// How does this work? Who is sender?
this.btnReturn_Click(sender, e);
}
else
{
Response.Write("Nothing Ordered<br>You must order some of the product or return to the Catalog");
}

这是 OrderItem 对象

public class OrderItem
{
private int productID;
private string prodName;
private double unitPrice;
private int quantityOrdered;

private string exceptionStr;


public OrderItem(int id, string name, double price, int quantity)
{
prodName = name;
exceptionStr = "Numeric data must not be negative";
if ( id < 0 || price < 0 || quantity < 0)
{
throw new System.ArgumentException(exceptionStr);
}
else
{
productID = id;
unitPrice = price;
quantityOrdered = quantity;
}
}


#region Public Properties
public int ProductID
{
get
{
return productID;
}
}

public string ProductName
{
get
{
return prodName;
}
}


public double UnitPrice
{
get
{
return unitPrice;
}
}


public int QuantityOrdered
{
get
{
return quantityOrdered;
}
set
{
if( value < 0 )
{
throw new ArgumentException(exceptionStr);
}
else
{
quantityOrdered = value;
}
}
}

#endregion
}

这是供您查看的购物车:

 public class ShoppingCart : IEnumerable
{
private SortedList theCart;

public ShoppingCart() {
theCart = new SortedList();
} // end of Constructor


public bool HasItems {
get{
bool hasItems = false;
if( theCart.Count > 0 )
hasItems = true;
return hasItems;
}
set {
// ignore this is read only
}
} // end of HasItems


public void addToCart(OrderItem item) {
theCart.Add(item.ProductID, item);
}// AddToCaArt

/// <summary>
/// deletes item that is passed
/// </summary>
/// <param name="item"></param>
public void deleteFromCart(OrderItem item)
{
theCart.Remove(item.ProductID);
} // end deleteFromCart

/// <summary>
/// deletes the item with this id key
/// </summary>
/// <param name="id"></param>
public void deleteFromCart(int id)
{
theCart.Remove(id);
} // end deleteFromCart
public OrderItem[] getCartContents()
{

// need to create stuff
OrderItem[] stuff = null;
theCart.Values.CopyTo(stuff, 0);

return (stuff);
} // end getCartContents


public bool keyExists(int ID) {

return theCart.ContainsKey(ID);
}// end keyExists

public ICollection Values
{
get
{
return theCart.Values;
}
}

#region IEnumerable Members

public IEnumerator GetEnumerator()
{
return theCart.GetEnumerator();
}

#endregion
}

最佳答案

我强烈建议从类或模型级别考虑购物车的外观。我认为像下面这样的一组类会有很大帮助(不是最好的,但从头开始设计还不错):

[Serializable]
public class ShoppingCartItem
{
public ShoppingCartItem(guid key, decimal price, int quantity)
{
this.Key = key;
this.Price = price;
this.Quantity = quantity;
}

public Guid Key { get; private set; }
public Decimal Price { get; private set; }
public int Quantity { get; set; }
}

[Serializable]
public class ShoppingCart
{
public ShoppingCart()
{
this.Clear();
}

public ICollection<ShoppingCartItem> Items { get; private set; }

public int ItemCount
{
get { return this.Items.Sum(i => i.Quantity); }
}

public decimal Subtotal
{
get { return this.Items.Sum(i => i.Quantity * i.Price); }
}

public void Clear()
{
this.Items = new List<ShoppingCartItem>();
}
}

现在 ShoppingCart 是可序列化的,可以存储在 ASP.Net session 中(或制作愿望 list :))

现在我不喜欢松散类型的 ASP.Net session ,所以我从某个我不记得的地方借用了这个很棒的类来制作强类型的 Session 对象:

using System;
using System.Web;

namespace Company.Product.Web.UI.Domain
{
public abstract class SessionBase<T> where T : class, new()
{
private static readonly Object _padlock = new Object();

private static string Key
{
get { return typeof(SessionBase<T>).FullName; }
}

public static T Current
{
get
{
var instance = HttpContext.Current.Session[Key] as T;

if (instance == null)
{
lock (SessionBase<T>._padlock)
{
if (instance == null)
{
HttpContext.Current.Session[Key] =
instance = new T();
}
}
}

return instance;
}
}

public static void Clear()
{
var instance = HttpContext.Current.Session[Key] as T;
if (instance != null)
{
lock (SessionBase<T>._padlock)
{
HttpContext.Current.Session[Key] = null;
}
}
}

}
}

为了在这个例子中使用它,我将创建:

public class ShoppingCartSession : SessionBase<ShoppingCart> { }

然后我可以在我的代码中的任何地方使用它:

var item = ShoppingCartSession.Current.Items.FirstOrDefault(i => i.Key= key);

if (item == null)
{
ShoppingCartSession.Current.Items.Add(
new ShoppingCartItem(Key, price, quantity));
}
else
{
item.Quantity = item.Quantity + quantity;
}

可扩展的强类型 session 购物车对象,允许您做您想做的事等等。您的应用程序的其他部分也可以访问它以显示购物车中的商品数量和某个区域的小计,例如在您的应用程序顶部显示购物车状态的小预览。

关于c# - 如何在 ASP.NET C# 中使用 session 更改替换对象的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12991275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com