0

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??

enter image description here

phuzi
  • 12,078
  • 3
  • 26
  • 50
LucasRBA
  • 1
  • 1
  • 1
    I think your issue is due to the fact that you have multiple forms, and that the value you are updating may not be in the form you are submitting to the server. Check from the browser what data is being sent to the server. – Ezra Nov 06 '22 at 10:44
  • There is a function that updates the value right before the end os th cshtml file, after adding a console.log I confirmed that it's working. What concerns me is that I checked after reading your comment the value being received by the Request.Form, and it looks like an object filled only with a token and its security value. I tried adding [0] in order to access it, but it's not working. I updated the question with the print of the result while debugging. – LucasRBA Nov 06 '22 at 21:09
  • Does this answer your question? [Set Value of Input Using Javascript Function](https://stackoverflow.com/questions/5700471/set-value-of-input-using-javascript-function) – n0rd Nov 06 '22 at 21:19
  • I just tried the .value, to change the current value, but nothing changed, my problem is really passing that value to my controller, so that quantity can be stored as the quantity of a product in an order, just like an e-commerce... – LucasRBA Nov 07 '22 at 01:09
  • Check the dev tools in a browser for the contents of the request sent. – n0rd Nov 07 '22 at 06:53
  • I checked the network tab inside tdev tools, and the request didn't have any content, actually what I don't undestand is why the Request.Form always returns null or zero, cause the value in the console is contantly being updated, before the content is sent, but for my controlller it always returns 0 and the contents of the request.form are {} ... – LucasRBA Nov 13 '22 at 18:57

0 Answers0