出于某些原因,在Controller Edit中,当我保存购物车数量时,它不保存任何内容,并在HttpPost Edit中为viewmodel返回null。我该如何解决这个问题?它适用于我所有其他具有不同模型的控制器,但是我认为Sessions不能正常工作。我的AddtoCart和RemoveFromCart函数正常工作。
shoppingCartViewModel在“编辑帖子”中为空
型号:
namespace ElectronicsStore.Models
{
public class ShoppingCart : List<CartLine>
{
public ShoppingCart() { }
public ShoppingCart(IEnumerable<CartLine> collection) : base(collection) { }
public ShoppingCart(int capacity) : base(capacity) { }
}
}
public class CartLine
{
public int CartLineId { get; set; }
public Product Product { get; set; }
public int Quantity { get; set; }
public float TotalDollar { get => Quantity * Product.getUnitPrice();}
}
存储库:
public class ShoppingCartRepository : IShoppingCartRepository<ShoppingCart>
{
private ShoppingCart shoppingCart = new ShoppingCart();
//private List<CartLine> lineCollection = new List<CartLine>();
public ShoppingCart GetAll()
{
return shoppingCart;
}
public virtual void AddItem(Product product, int quantity)
{
shoppingCart.Find(p => p.Product == product);
CartLine cartline = shoppingCart.Where(p => p.Product.ProductId == product.ProductId).FirstOrDefault();
if (cartline == null)
{
shoppingCart.Add(new CartLine
{
Product = product,
Quantity = quantity
});
}
else
{
cartline.Quantity += quantity;
}
}
public virtual void RemoveItem(int cartlineid)
{
shoppingCart.RemoveAll(l => l.CartLineId == cartlineid);
}
public virtual void UpdateItem(ShoppingCartViewModel shoppingcartviewmodel)
{
shoppingCart = shoppingcartviewmodel.ShoppingCart;
}
public virtual IEnumerable<CartLine> Lines => shoppingCart;
}
}
控制器:
public class ShoppingCartController : Controller
{
private IProductRepository<Product> _productRepository;
private ShoppingCartRepository _shoppingCartRepository;
public ShoppingCartController(IProductRepository<Product> productRepository, ShoppingCartRepository shoppingCartRepository)
{
_productRepository = productRepository;
_shoppingCartRepository = shoppingCartRepository;
}
public async Task<IActionResult> Edit(string returnUrl)
{
ShoppingCartViewModel shoppingCartViewModel = new ShoppingCartViewModel();
shoppingCartViewModel.ShoppingCart = _shoppingCartRepository.GetAll();
shoppingCartViewModel.ReturnUrl = returnUrl;
return View(shoppingCartViewModel);
}
// POST: Products1/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(ShoppingCartViewModel shoppingCartViewModel, string returnUrl)
{
_shoppingCartRepository.UpdateItem(shoppingCartViewModel);
return RedirectToAction("Edit", new { returnUrl });
}
public RedirectToActionResult AddToCart(int productid, string returnUrl)
{
Product product = _productRepository.GetById(productid);
_shoppingCartRepository.AddItem(product, 1);
return RedirectToAction("Edit", new { returnUrl });
}
public RedirectToActionResult RemoveFromCart(int cartlineid, string returnUrl)
{
_shoppingCartRepository.RemoveItem(cartlineid);
return RedirectToAction("Index", new { returnUrl });
}
}
}
查看:
@model ShoppingCartViewModel
@{
ViewData["Title"] = "Index";
}
<h2>Shopping Cart</h2>
<h2>Edit</h2>
<h4>Product</h4>
<hr />
<div class="row">
<div class="col-md-4">
@foreach (var item in Model.ShoppingCart)
{
<form asp-action="Edit" class="row">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="@item.CartLineId" />
<div class="form-group col-md-4">
<label asp-for="@item.Product.ProductName" class="control-label"></label>
<input asp-for="@item.Product.ProductName" class="form-control" />
<span asp-validation-for="@item.Product.ProductName" class="text-danger"></span>
</div>
<div class="form-group col-md-4">
<label asp-for="@item.Quantity" class="control-label"></label>
<input asp-for="@item.Quantity" class="form-control" />
<span asp-validation-for="@item.Quantity" class="text-danger"></span>
</div>
<div class="form-group col-md-4">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</form>
}
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
启动:
services.AddTransient<ISupplyRepository<Supply>, SupplyRepository>();
services.AddTransient<ShoppingCartRepository>(sp => ShoppingCartSession.GetCart(sp));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
会话:
public class ShoppingCartSession : ShoppingCartRepository
{
public static ShoppingCartRepository GetCart(IServiceProvider services)
{
ISession session = services.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;
ShoppingCartSession shoppingcartsession = session?.GetJson<ShoppingCartSession>("ShoppingCartRepository") ?? new ShoppingCartSession();
shoppingcartsession.Session = session;
return shoppingcartsession;
}
[JsonIgnore]
public ISession Session { get; set; }
public override void AddItem(Product product, int quantity)
{
base.AddItem(product, quantity);
Session.SetJson("ShoppingCartRepository", this);
}
public override void RemoveItem(int cartlineid)
{
base.RemoveItem(cartlineid);
Session.SetJson("ShoppingCartRepository", this);
}
public override void UpdateItem(ShoppingCartViewModel shoppingcartviewmodel)
{
base.UpdateItem(shoppingcartviewmodel);
Session.SetJson("ShoppingCartRepository", this);
}
}
会话扩展:
public static void SetJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetJson<T>(this ISession session, string key)
{
var sessionData = session.GetString(key);
return sessionData == null
? default(T) : JsonConvert.DeserializeObject<T>(sessionData);
}