D
D
Dmitry2019-09-27 13:14:13
HTML
Dmitry, 2019-09-27 13:14:13

ASP.NET Core MVC. How to update only the ViewComponent, without reloading the entire page?

There is a view of the product page. It displays, through a partial view, a shopping cart. On the cart itself, when adding a product to it (pressing the "add to cart" button), a circle appears with the number of orders, and in the controller, new records are added to the stream, as well as the page is returned. The problem is that now the controller method updates the entire page, but I need to update only the number on the basket

public IActionResult AddToCart(int productId, string returnUrl, int quantityInProduct)
        {
            Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId);
            if (product != null)
            {
                cart.AddItem(product, quantityInProduct);
            }
            return RedirectToAction("List", "Product", new { returnUrl });
        }

if I write like this it only returns a partial view without the whole page. here is the partial view code:return ViewComponent("CartSummary");
@model Cart

<div style="width: 100px; z-index: 3;">
    <span>
        @Model.ComputeTotalValue().ToString("c")
    </span>
    <a class="iconCart"
       asp-controller="Cart" asp-action="Index"
       asp-route-returnurl="@ViewContext.HttpContext.Request.PathAndQuery()">
    </a>
    @if (Model.Lines.Count() > 0)
    {
        <span class="cartSum">
            @Model.Lines.Sum(x => x.Quantity)
        </span>
    }
</div>

and here is the component:
public class CartSummaryViewComponent : ViewComponent
    {
        private Cart cart;
        public CartSummaryViewComponent(Cart cartService)
        {
            cart = cartService;
        }
        public IViewComponentResult Invoke()
        {
            return View(cart);
        }
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question