Search code examples
javascriptc#jqueryasp.net-coremodel-view-controller

ASP.NET Core - Change Url of Product Details when select Color


I am working on E-commerce Laptop. I want when the user chooses another color in the select drop-down, it will redirect to the product of that color.

example website

I am using JavaScript to redirect the URL, here is the code:

$(document).on('change', '#color', function () {
    var selectedRam = $('#@Model.RamId').val(); 
    var selectedSSD = $('#@Model.Ssdid').val(); 
    var selectedColor = $(this).val();

    
    var url = '@Url.Action("ProductDetail", "ProductView", new { id = "selectedColor", ramId = "selectedRam", ssdId = "selectedSSD" })';

    window.location.href = url;
});

The controller :

public async Task<IActionResult> ProductDetail(int? id, int ramId, int ssdId)
{
    if (id == null)
    {
        return BadRequest();
    }
    var sp = await _context.ProductVariations
        .Include(n => n.ProductItems.Product)
        .Where(n => n.ProductItemsId == id && n.RamId == ramId && n.Ssdid == ssdId)
        .FirstOrDefaultAsync();


    ViewBag.Lisp = _context.ProductItems
        .Include(n => n.Product.Category)
        .Where(n => n.Product.CategoryId == sp.ProductItems.Product.CategoryId);

    ViewBag.Color = await _context.ProductItems
        .Where(n => n.ProductId == sp.ProductItems.ProductId)
        .Include(n => n.Color)
        .ToListAsync();


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

    return View(sp);
}

The value of color in selected box is productItemsId.

color options

When I get the productItemsId, SsdId, and RamId, I will find the product of that color in the productVariation table in the database. But the problem is when I choose another color, it doesn't work.

I believed my JavaScript was wrong. I searched ChatGPT and Copilot but still the same. Does anyone know the solution? I would appreciate any instruction. Thank you.


Solution

  • Assume that you are able to get the value for these 3 variables correctly: selectedRam, selectedSSD and selectedColor,

    Unfortunately, you can't pass the JavaScript variable values which are client-side code to the server-side code @Url.Action().

    You need to construct the URL manually with parameters and/or query parameters.

    var url = '@Url.Action("ProductDetail", "ProductView")' 
      + `/${selectedColor}?ramId=${selectedRam}&ssdId=${selectedSSD}`;