I'm currently trying to get the boughtQuantity attribute as a variable to my controller, but it always returns zero. This value is dynamically changed with javascript, and then sent by innerText to a hidden field.
Cart.cshtml
@using System.Globalization
@using System.Text.Json;
@using Microsoft.AspNetCore.Components;
@using Microsoft.AspNetCore.Http;
@model IEnumerable<E_Commerce_Payment_API.Models.Product>
@using System.Collections.Generic;
@{
ViewData["Title"] = "Products in your cart";
}
<div class="text-center">
<p style="font-size:250%;" class="display-4">In this page you will be able see all products and add them to your cart</p>
</div>
<br>
<br>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.StockQuantity)
</th>
<th type="hidden">
</th>
<th>
Quantity in cart
</th>
<th type="hidden">
</th>
<th>
@Html.DisplayNameFor(model => model.Weight)
</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
@if(Model !=null) {
@foreach(var item in Model)
{
<tr>
<td>
@Html.DisplayFor(model => item.Name)
</td>
<td>
@{
var formattedPrice = "";
if(item.Price.Equals(null) || item.Price.Equals(" ") ) {
formattedPrice = " X ";
} else {
formattedPrice = item.Price.ToString("C2", CultureInfo.CurrentCulture);
}
}
@Html.DisplayFor(model => formattedPrice)
</td>
<td type="hidden" id="totalQuantity">
@Html.DisplayFor(model => item.StockQuantity)
</td>
<td>
</td>
<td >
<button id="increase" type="button" class="btn btn-primary">
<span class="fa fa-plus" style="color:white"></span></button>
@{
var boughtQuantity = 1;
}
<form id="quantity" name="btQuantity">@Html.DisplayFor(model => boughtQuantity)</form>
<button id="decrease" type="button" class="btn btn-primary">
<span class="fa fa-minus" style="color:white"></span></button>
</td>
<td>
</td>
<td>
@{
var formattedWeight = "";
formattedWeight = String.Format("{0:N2} Kg", item.Weight);
}
@Html.DisplayFor(model => formattedWeight)
</td>
<td>
<form asp-action="Buy" asp-route-id="@item.Id" onclick="return confirm('Are you sure you want to buy this product?');">
<input id="buyButton" type="submit" value="Buy" class="btn btn-success"/>
</form>
</td>
<td>
<a asp-controller="Sale" asp-action="Delete" asp-route-id="@item.Id"><button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure you want to remove it from your cart?');">Remove</button></a>
</td>
<td type="hidden"><form method="get"><input type="hidden" id="sentQuantity" name="boughtQuantity"></input></form></td>
</tr>
}
} else {
}
</tbody>
</table>
@section scripts{
<script type="text/javascript">
let totalQuantity = @Html.Raw(Json.Serialize(Model)); // Até aqui certo
totalQuantity = totalQuantity[0].stockQuantity;
var boughtQuantity = document.getElementById('quantity').innerText;
boughtQuantity = Number(boughtQuantity);
const increase = document.getElementById('increase');
const decrease = document.getElementById('decrease');
const buy = document.getElementById('buyButton');
increase.addEventListener("click", increaseQuantity);
decrease.addEventListener("click", decreaseQuantity);
buy.addEventListener("click", saveToLocal);
function getValue() {
console.log(totalQuantity);
return totalQuantity;
}
function increaseQuantity(){
if(Number(boughtQuantity) < totalQuantity) {
Number(boughtQuantity++);
document.getElementById('quantity').innerText = boughtQuantity;
upgradeSentQuantity();
}
}
function decreaseQuantity(){
if(Number(boughtQuantity) > 0) {
Number(boughtQuantity--);
document.getElementById('quantity').innerText = boughtQuantity;
upgradeSentQuantity();
}
}
function saveToLocal() {
if(boughtQuantity > 0) {
window.localStorage.setItem('boughtQuantity', Number(boughtQuantity));
console.log(boughtQuantity);
}
}
function upgradeSentQuantity(){
document.getElementById("sentQuantity").innerText = boughtQuantity;
}
</script>
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<a class="nav-link text-light col" asp-area="" asp-controller="Product" asp-action="ProductsList"><button class="btn btn-secondary">Back</button></a>
The controller trying to access it...
using E_Commerce_Payment_API.Models;
using E_Commerce_Payment_API.Context;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace E_Commerce_Payment_API.Controllers
{
public class SaleController : Controller
{
private readonly E_CommerceContext _context;
private readonly IHttpContextAccessor contextAccessor;
public SaleController(E_CommerceContext context) {
_context = context;
}
public Double CalculateShippingCost(int min, int max) {
var rand = new Random();
var intpart = rand.Next(min,max);
var decimalpart = Math.Round(rand.NextDouble(), 2);
double ShippingCost = intpart + decimalpart;
return ShippingCost;
}
public IActionResult EmptyCart() {
return View();
}
[HttpGet]
public IActionResult Cart(int id) {
var product = _context.Products.Find(id);
var productsInCart = new List<Product>() {};
if(product != null) {
productsInCart.Add(product);
return View(productsInCart);
} else {
return RedirectToAction(nameof(EmptyCart));
}
}
[HttpPost]
public IActionResult Buy(int id){
var bought = _context.Products.Find(id);
int boughtQuantity = Convert.ToInt32(Request.Form["boughtQuantity"]); //TODO get value from field
Sale newSale = new Sale();
newSale.SaleDate = DateTime.UtcNow;
newSale.ProductId = bought.Id;
newSale.ProductQuantity = boughtQuantity;
var saleWeight = bought.Weight * boughtQuantity;
var lightShippingCost = CalculateShippingCost(5,50);
var heavyShippingCost = CalculateShippingCost(50,100);
newSale.TotalValue = ((boughtQuantity) * (bought.Price)) + Convert.ToDecimal(saleWeight < 15 ? lightShippingCost : heavyShippingCost);
newSale.Status = SaleStatusEnum.AwaitingPayment;
if(ModelState.IsValid){
_context.Sales.Add(newSale);
_context.SaveChanges();
return View(newSale);
}
return View();
}
[HttpPost]
public IActionResult RemovefromCart(int id){
var product = _context.Products.Find(id);
return RedirectToAction(nameof(Cart));
}
[HttpGet]
public IActionResult Buy() {
return View();
}
}
}
I already tried doing it by localStorage but it didn't worked, so now I am trying to access its value by Request.Form. How can I get the value??