本文整理匯總了C#中Cart類的典型用法代碼示例。如果您正苦於以下問題:C# Cart類的具體用法?C# Cart怎麽用?C# Cart使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Cart類屬於命名空間,在下文中一共展示了Cart類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: btnAddToCart_Click
protected void btnAddToCart_Click(object sender, EventArgs e)
{
Cart cart;
if (Session["Cart"] is Cart)
cart = Session["Cart"] as Cart;
else
cart = new Cart();
short quantity = 1;
try
{
quantity = Convert.ToInt16(txtQuantity.Text);
}
catch (Exception ex)
{
lblMessage.Text = string.Format("An error has occurred: {0}", ex.ToString());
}
//TODO: Put this in try/catch as well
//TODO: Feels like this is too much business logic. Should be moved to OrderDetail constructor?
var productRepository = new ProductRepository();
var product = productRepository.GetProductById(_productId);
var orderDetail = new OrderDetail()
{
Discount = 0.0F,
ProductId = _productId,
Quantity = quantity,
Product = product,
UnitPrice = product.UnitPrice
};
cart.OrderDetails.Add(orderDetail);
Session["Cart"] = cart;
Response.Redirect("~/ViewCart.aspx");
}
示例2: ChangeStatus
public string ChangeStatus(int id = 0, int statusID = 0) {
Profile p = ViewBag.profile;
Cart order = new Cart();
order = order.GetByPayment(id);
order.SetStatus(statusID, p.first + " " + p.last);
return "success";
}
示例3: UpdateSession
private void UpdateSession()
{
if (HttpContext.Session["Cart"] == null)
HttpContext.Session["Cart"] = cart;
else
cart = HttpContext.Session["Cart"] as Cart<Product>;
}
示例4: Checkout
public ViewResult Checkout(Cart cart, Address address, bool mainAddress, string shipMethod)
{
if(!cart.Lines.Any()) ModelState.AddModelError("","Sorry, your cart is empty!");
var user = AuthHelper.GetUser(HttpContext, new EfUserRepository());
if (mainAddress) //если основной, то перезаписываем
{
if (address.AddressID == 0) //на случай, если пользователь не заполнил свой адрес в профиле
{
address.ModifiedDate = DateTime.Now;
address.rowguid = Guid.NewGuid();
_addressRepository.SaveToAddress(address);
_addressCustomerRepository.SaveToCustomerAddress(_addressCustomerRepository.BindCustomerAddress(
user, address));
}
else
{
_addressRepository.SaveToAddress(address);
}
}
else // иначе добавляем новый
{
address.AddressID = 0;
address.ModifiedDate = DateTime.Now;
address.rowguid = Guid.NewGuid();
_addressRepository.SaveToAddress(address);
}
if (ModelState.IsValid)
{
_orderProcessor.Processor(cart, user,address, shipMethod);
cart.Clear();
return View("Completed");
}
return View("Checkout");
}
示例5: Cannot_Checkout_Empty_Cart
public void Cannot_Checkout_Empty_Cart()
{
// Arrange - create a mock order processor
Mock<IOrderProcessor> mock = new Mock<IOrderProcessor>();
// Arrange - create an empty cart
Cart cart = new Cart();
// Arrange - create shipping details
ShippingDetails shippingDetails = new ShippingDetails();
// Arrange - create an instance of the controller
CartController target = new CartController(null, mock.Object);
// Act
var result = target.Checkout(cart, shippingDetails);
// Assert check that the order hasn't been passed on to the processor
mock.Verify(m => m.ProcessOrder(It.IsAny<Cart>(), It.IsAny<ShippingDetails>()), Times.Never);
// Assert - check that the method is returning the default view
Assert.AreEqual("", result.ViewName);
// Assert - check that we are passing an invalid model to the view
Assert.AreEqual(false, result.ViewData.ModelState.IsValid);
}
示例6: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
try
{
this.CurrentCart = Cart.GetCartFromSession(Session);
if (this.CurrentCart == null) throw new CartException("Cannot load cart data from session");
if (this.CurrentCart.BillingLocation == null) throw new CartException("Incomplete Cart (Billing)");
if (this.CurrentCart.ShippingLocation == null) throw new CartException("Incomplete Cart (Shipping)");
if (this.CurrentCart.Payment == null) throw new CartException("Incomplete Cart (Payment)");
if (this.CurrentCart.Dirty) this.CurrentCart.Clean();
string locationsummarypath = String.Format("{0}/locationsummary.ascx", Constants.UserControls.CHECKOUT_CONTROLS_DIR);
string paymentsummarypath = String.Format("{0}/paymentsummary.ascx", Constants.UserControls.CHECKOUT_CONTROLS_DIR);
string shippingoptionsummarypath = String.Format("{0}/shippingoptionsummary.ascx", Constants.UserControls.CHECKOUT_CONTROLS_DIR);
string itemsummarypath = String.Format("{0}/itemsummary.ascx", Constants.UserControls.CHECKOUT_CONTROLS_DIR);
BillingSummaryPlaceholder.Controls.Add(Helper.LoadUserControl(Page, locationsummarypath, CurrentCart.BillingLocation));
ShippingSummaryPlaceholder.Controls.Add(Helper.LoadUserControl(Page, locationsummarypath, CurrentCart.ShippingLocation));
ShippingOptionSummaryPlaceholder.Controls.Add(Helper.LoadUserControl(Page, shippingoptionsummarypath, CurrentCart));
orderid = Convert.ToInt32(Request.QueryString["id"]);
POrder = Convert.ToInt32(Request.QueryString["po"]);
//PaymentSummaryPlaceholder.Controls.Add(Helper.LoadUserControl(Page, paymentsummarypath, CurrentCart.Payment));
ItemsSummaryPlaceholder.Controls.Add(Helper.LoadUserControl(Page, itemsummarypath, CurrentCart));
}
catch (CartException ex)
{
Page.Controls.Add(new LiteralControl("There was an error loading your cart"));
}
}
示例7: AddToCart
public void AddToCart(Album album)
{
// Get the matching cart and album instances
var cartItem = storeDB.Carts.SingleOrDefault(
c => c.CartId == ShoppingCartId
&& c.AlbumId == album.AlbumId);
if (cartItem == null)
{
// Create a new cart item if no cart item exists
cartItem = new Cart
{
AlbumId = album.AlbumId,
CartId = ShoppingCartId,
Count = 1,
DateCreated = DateTime.Now
};
storeDB.Carts.Add(cartItem);
}
else
{
// If the item does exist in the cart, then add one to the quantity
cartItem.Count++;
}
// Save changes
storeDB.SaveChanges();
}
示例8: ButtonAdd2Cart_Click
/// <summary>
/// "放入購物車"按鈕單擊事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ButtonAdd2Cart_Click(object sender, System.EventArgs e)
{
if (Session["user_id"] == null)
Page.Response.Redirect("Login.aspx?in=1");
Cart cart = new Cart();
Hashtable ht = new Hashtable();
ArrayList selectedBooks = this.GetSelected();
//如果用戶沒有選擇,就單擊該按鈕,則給出警告
if (selectedBooks.Count == 0)
{
Response.Write("<Script Language=JavaScript>alert('請選擇圖書!');</Script>");
return;
}
//循環將選擇的圖書加入到購物籃中
foreach (int bookId in selectedBooks)
{
ht.Clear();
ht.Add("UserId", Session["user_id"].ToString());
ht.Add("BookId", bookId);
ht.Add("Amount", TextBoxAmount.Text.Trim());
cart.Add(ht);
}
Response.Redirect("CartView.aspx");
}
示例9: PutCart
public async Task<IHttpActionResult> PutCart(int id, Cart cart)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != cart.Id)
{
return BadRequest();
}
db.Entry(cart).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CartExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
示例10: btnAdd_Click
protected void btnAdd_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
string clientId = Context.User.Identity.GetUserId();
if (clientId != null)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
int amount = Convert.ToInt32(ddlAmount.SelectedValue);
Cart cart = new Cart
{
Amount = amount,
ClientID = clientId,
DatePurchased = DateTime.Now,
IsInCart = true,
ProductID = id
};
CartModel model = new CartModel();
lblResult.Text = model.InsertCart(cart);
}
else
{
lblResult.Text = "Please log in to order items";
}
}
}
示例11: AddToCart
public void AddToCart(Product product)
{
// Get the matching cart and product instances
var cartItem = _cartAppService.Find(
c => c.CartId == ShoppingCartId &&
c.ProductId == product.ProductId).SingleOrDefault();
if (cartItem == null)
{
// Create a new cart item if no cart item exists
cartItem = new Cart
{
ProductId = product.ProductId,
CartId = ShoppingCartId,
Count = 1,
DateCreated = DateTime.Now
};
_cartAppService.Create(cartItem);
}
else
{
// If the item does exist in the cart, then add one to the quantity
cartItem.Count++;
}
}
示例12: btnAdd_Click
protected void btnAdd_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
//get the id of the current logged in user
string clientId = Context.User.Identity.GetUserId();
//implement a check to make sure only logged in user can order a product
if (clientId != null)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
int amount = Convert.ToInt32(ddlAmount.SelectedValue);
Cart cart = new Cart
{
Amount = amount,
ClientID = clientId,
DatePurchased = DateTime.Now,
IsInCart = true,
ProductID = id
};
CartModel cartModel = new CartModel();
lblResult.Text = cartModel.InsertCart(cart);
Response.Redirect("~/Index.aspx");
}
else
{
lblResult.Text = "Please log in to order items";
}
}
}
示例13: ReleaseCart
public Cart ReleaseCart(decimal receivedTax)
{
if (receivedTax < CartTax)
{
throw new ApplicationException("Call the police!");
}
else
{
this.collectedTax += receivedTax;
}
Cart currentCart;
if (this.freeCarts.Count == 0)
{
currentCart = new Cart();
}
else
{
int lastCart = this.freeCarts.Count - 1;
currentCart = this.freeCarts[lastCart];
this.freeCarts.RemoveAt(lastCart);
}
return currentCart;
}
示例14: AddToCart
public void AddToCart(int id)
{
// Retrieve the product from the database.
ShoppingCartId = GetCartId();
var cartItem = db.Carts.SingleOrDefault(
c => c.CartID == ShoppingCartId
&& c.ProductID == id);
if (cartItem == null)
{
cartItem = new Cart
{
ItemID = Guid.NewGuid().ToString(),
ProductID = id,
CartID = ShoppingCartId,
Product = db.Products.SingleOrDefault(
p => p.ProductID == id),
Quantity = 1,
DateCreated = DateTime.Now
};
db.Carts.Add(cartItem);
}
else
{
cartItem.Quantity++;
}
db.SaveChanges();
}
示例15: AddToCart
public RedirectToRouteResult AddToCart(int Id, int quantity)
{
cart = getCart();
Product p = db.Products.Where(x => x.Id == Id).SingleOrDefault();
cart.AddItem(p, quantity);
return RedirectToAction("Index", "Shop");
}