~/src/components/Products/AddToCart.js
import React, { Component } from 'react';
import Axios from 'axios';
export default class AddToCart extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
async onSubmit(e) {
e.preventDefault();
let sessionId = localStorage.sessionId;
let result = await Axios.post('/api/cart', { productId: this.props.productId, sessionId: sessionId });
localStorage.sessionId = result.data.sessionId;
}
render() {
return <form onSubmit={this.onSubmit}>
<div className="form-row">
<div className="form-group">
<button className="btn btn-primary form-control" type="submit">
Add to Cart
</button>
</div>
</div>
</form>;
}
}
在後端C#專案新增一個Model
存放ProductID
public class AddItemCommand
{
public int ProductId { get; set; }
}
新增CartService(要來將DB存取業務一樣從Action抽離降低耦合)
public class CartService
{
private readonly StoreContext dbContext;
public CartService(StoreContext dbContext)
{
this.dbContext = dbContext;
}
public void AddItem(AddItemCommand command)
{
var cart = new ShoppingCart { SessionId = Guid.NewGuid(), CreatedOn = DateTime.Now };
cart.Items.Add(new CartLineItem { ProductId = command.ProductId, Quantity = 1 });
dbContext.ShoppingCart.Add(cart);
dbContext.SaveChanges();
}
}
Program.cs起初服務註冊也要記得補配置
services.AddScoped<CartService>();
編輯修改CartController
[Route("api/[controller]")]
[ApiController]
public class CartController : ControllerBase
{
private readonly StoreContext dbContext;
private readonly CartService cartService;
public CartController(CartService cartService)
{
this.cartService = cartService;
}
[HttpPost]
public IActionResult AddItem(AddItemCommand command)
{
cartService.AddItem(command);
return Ok();
}
}
public class AddItemCommand
{
public int ProductId { get; set; }
}