View:
@model Product
<div class="well">
<form id="@Model.ProductID" asp-controller="Cart" asp-action="AddToCart" method="post">
<input type="hidden" asp-for="ProductID" />
<input type="hidden" name="returnUrl" value="@ViewContext.HttpContext.Request.PathAndQuery()" />
<span class="lead">
@Model.Description
<button type="submit" class="btn btn-success btn-srn pull-right"> Add То Cart </button>
</span>
</form>
</div>
CartController:
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebEmpty.Infrastructure;
using WebEmpty.Models;
using WebEmpty.Models.ViewModels;
namespace WebEmpty.Controllers
{
public class CartController : Controller
{
List<Product> products;
public ViewResult Index(string returnUrl)
{
return View(new CartIndexViewModel { Cart = GetCart(), ReturnUrl = returnUrl });
}
public RedirectToActionResult AddToCart(int productId, string returnUrl)
{
products = new List<Product>();
int col = Operations.Count();
for (int i = 1; i <= col; i++)
products.Add(Operations.Read(i));
Product product = products.ToArray().FirstOrDefault(p => p.ProductID == productId);
if(product != null)
{
Cart cart = GetCart();
cart.Additem(product, 1);
SaveCart(cart);
}
return RedirectToAction("Index", new { returnUrl });
}
Cart GetCart()
{
Cart cart = HttpContext.Session.GetJson<Cart>("Cart") ?? new Cart();
return cart;
}
void SaveCart(Cart cart)
{
HttpContext.Session.SetJson("Cart", cart);
}
}
}
По какой-то причине не вызывается метод AddToCart() по нажатию на кнопку.
Сгенерировавшейся html:
<div class="well">
<form id="2" action="" method="post">
<input name="ProductID" id="ProductID" type="hidden" value="2" data-val-required="The ProductID field is required." data-val="true">
<input name="returnUrl" type="hidden" value="/">
<span class="lead">
Protective and fashionable
<button class="btn btn-success btn-srn pull-right" type="submit"> Add То Cart </button>
</span>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8E3bmc_2XN5Fk1av-zNawj1Z6N77o52MbM-UQV5tXxhbdKcSoSFbmsVylQFoAkEBrNDpOWmRRZiL4l4iTpV9QN9-TQt3ufF-GP9aZVLLlUHPkrRRdFCuuAAGsXvvMf_BUFNuBgKUeLW-jSwuK9qP0ws"></form>
</div>