ASP.NET Core MVC calling an action from to a view

84 views Asked by At

I try to create an e-commerce websites. I have a page for a product with a button "Add to cart". On this page (SingleProduct.cshtml), I also take quantity of product from customer. This page use Product model (@model Product). I want to call an action with quantity and @model.ProductId.

Here is my view:

@model Product
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link href="https://fonts.googleapis.com/css?family=Poppins:100,200,300,400,500,600,700,800,900&display=swap" rel="stylesheet">

    <title>Dene @Model.ProductName</title>

</head>

<body>

    <!-- ***** Main Banner Area Start ***** -->
    <div class="page-heading" id="top">
        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <div class="inner-content">
                        <h2>@Model.ProductName</h2>
                        <span>Here is placed for effective words</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- ***** Main Banner Area End ***** -->
    <!-- ***** Product Area Starts ***** -->
    <section class="section" id="product">
        <div class="container">
            <div class="row">
                <div class="col-lg-8">
                    <div class="left-images">
                        <img src="~/templatemo_571_hexashop/assets/images/single-product-01.jpg" alt="">
                        <img src="~/templatemo_571_hexashop/assets/images/single-product-02.jpg" alt="">
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="right-content">
                        <h4>@Model.ProductName</h4>
                        <span class="price">[email protected]</span>
                        <ul class="stars">
                            <li><i class="fa fa-star"></i></li>
                            <li><i class="fa fa-star"></i></li>
                            <li><i class="fa fa-star"></i></li>
                            <li><i class="fa fa-star"></i></li>
                            <li><i class="fa fa-star"></i></li>
                        </ul>
                        <span>@Model.Description</span>
                        <div class="quote">
                            <i class="fa fa-quote-left"></i><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiuski smod.</p>
                        </div>
                        <form asp-controller="product" asp-action="feedback" method="post">
                            <div class="quantity-content">
                                <div class="left-content">
                                    <h6>No. of Orders</h6>
                                </div>
                                <div class="right-content">
                                    <div class="quantity buttons_added">
                                        <input type="button" value="-" class="minus"><input type="number" step="1" min="1" max="" name="quantity" value="1" title="Qty" class="input-text qty text" size="4" pattern="" inputmode=""><input type="button" value="+" class="plus">
                                    </div>
                                </div>
                            </div>
                        
                        <div class="total">
                            <h4>Total: $210.00</h4>
                            <div class="main-border-button"><a asp-controller="Product" asp-action="feedback" asp-route-id="@Model.ProductId" asp-route-quantity=quantity>Add To Cart</a></div>
                        </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!-- ***** Product Area Ends ***** -->
    <!-- ... (previous code) ... -->
    <!-- ***** Product Area Ends ***** -->
    <!-- jQuery -->
    <script src="~/templatemo_571_hexashop/assets/js/jquery-2.1.0.min.js"></script>

    <!-- Bootstrap -->
    <script src="~/templatemo_571_hexashop/assets/js/popper.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/bootstrap.min.js"></script>

    <!-- Plugins -->
    <script src="~/templatemo_571_hexashop/assets/js/owl-carousel.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/accordions.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/datepicker.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/scrollreveal.min.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/waypoints.min.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/jquery.counterup.min.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/imgfix.min.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/slick.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/lightbox.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/isotope.js"></script>
    <script src="~/templatemo_571_hexashop/assets/js/quantity.js"></script>

    <!-- Global Init -->
    <script src="~/templatemo_571_hexashop/assets/js/custom.js"></script>

    <script>
        $(function () {
            var selectedClass = "";
            $("p").click(function () {
                selectedClass = $(this).attr("data-rel");
                $("#portfolio").fadeTo(50, 0.1);
                $("#portfolio div").not("." + selectedClass).fadeOut();
                setTimeout(function () {
                    $("." + selectedClass).fadeIn();
                    $("#portfolio").fadeTo(50, 1);
                }, 500);
            });
        });
    </script>

</body>

</html>

Here is my controller:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Store02.Model;
using System.Collections.Generic;

namespace Store02.Controllers
{
    public class ProductController : Controller
    {
        private readonly ProductContext _context;

        public ProductController(ProductContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            Product Deneme = new Product();

            var model = _context.Products.ToList();
            
            return View(model);
        }

        public IActionResult Get(int id)
        {
            Product product = _context.Products.First(p => p.ProductId.Equals(id));

            return View(product);
        }

        /* public IActionResult Products(int id=0)
        {
            Product Deneme = new Product();

            List<Product> model;

            if (id != 0)
            {
                 model = _context.Products
                    .Where(p => p.CategoryId == id)
                    .ToList();
            }
            else
            {            
                 model = _context.Products.ToList();
            }

            return View(model);
        }*/
       
        public IActionResult SingleProduct(int id)
        {
            Product product = _context.Products.FirstOrDefault(p => p.ProductId == id);

            if (product == null)
            {
                // Handle the case when the product is not found, for example, redirect to an error page.
                return NotFound();
            }

            return View(product);
        }

        [HttpPost]
        public IActionResult feedback(int id, int quantity)
        {
            Product product = _context.Products.FirstOrDefault(p => p.ProductId == id);

            if (product == null)
            {
                return NotFound();
            }

            RepositoryOrderDetail.Add(product,quantity);

            return View("feedback", RepositoryOrderDetail.orders);
        }
    }
}

I tried to call with asp-route- but it did not work.

<div class="main-border-button">
    <a asp-controller="Product" asp-action="feedback" 
       asp-route-id="@Model.ProductId" 
       asp-route-quantity=quantity>Add To Cart</a>
</div>
1

There are 1 answers

1
lloyd On

I would assume "Add to Cart" is not supposed to go to feedback but nonetheless here is what that would look like. Change as needed.

Make sure you have a method that explicitly says to POST using [HttpPost] tag Otherwise .net will assume GET method.

See: Understanding [HttpPost], [HttpGet] and Complex Actionmethod parameters in MVC

Example of this:

[HttpPost]
public IActionResult Feedback(Product model)
{

}

You want to POST the entire model. It will make your life easier. That way you can return the posted values with the model and any changes you make to the data and return it right to the view.

Don't use <form asp-controller="product" asp-action="feedback" method="post"> Let them render the form for you.

Instead of form tag let razor view do the work. This will also futureproof your html in case anything ever changes in a future version.

// Inside Index.cshtml
@using (Html.BeginForm("Feedback", "Product", FormMethod.Post)) 
{
    // your html here
}

see answer to question: Html Beginform with button click is not working in .net core mvc

This will let razor render the form html for you and take out the guesswork.