-1

I'm working on a Pizza Store with shopping cart that uses session to store the cart and return it has a partial view to update the cart through AJAX.

This method has worked perfectly until recently, I haven't made any specific changes to the method or the CartController itself. But I have been working on the admin page to add more products, which is working as intended and shouldn't affect this part at all.

I have used visual studio to step through the code, it calls the correct method and getting correct values, but it stops at this line var temp = JsonConvert.SerializeObject(cart); where it throws Failed to load resource: the server responded with a status of 500 () error which can be seen in the browser console.

Full path is:

[https://localhost:44341/cart/product/1?X-Requested-With=XMLHttpRequest&_=1549979834762]
   [Route("product/{id}")]
   public async Task<IActionResult> AddItem(int id)
    {
        var user = await _userManager.GetUserAsync(User);
        if (user == null) Challenge();

        ShoppingCart cart;

        var product = await _dishService.GetDishAsync(id);

        // If shopping cart doesn't exist
        if (HttpContext.Session.GetString("varukorg") == null)
        {
            cart = new ShoppingCart
            {
                Products = new List<Matratt>(),
                User = user,
                Kund = await _userService.FindUserAsync(user.Id)
            };
        }
        else
        {
            // Else get the session and cast it as cart
            var serializedValue = ( HttpContext.Session.GetString("varukorg") );
            cart = JsonConvert.DeserializeObject<ShoppingCart>(serializedValue);
        }
        cart.Products.Add(product);

        // Added product, putting the session back.
        var temp = JsonConvert.SerializeObject(cart);
        HttpContext.Session.SetString("varukorg", temp);
        return PartialView("_CartList", cart);
    }

And the method is called from the view through unobtrusive AJAX, which has worked perfectly up until now.

<a class="btn btn-sm btn-success"
      data-ajax="true"
      data-ajax-method="GET"
      data-ajax-mode="replace"
      data-ajax-update="#cartList"
      asp-controller="Cart" asp-action="AddItem" asp-route-id="@item.Id">+ 
</a>

And the ViewModel used

    public List<Matratt> Products { get; set; }
    public AppUser User { get; set; }
    public Kund Kund { get; set; }
    public bool CalculatedPoints { get; set; }
Ronnehag
  • 29
  • 1
  • 4
  • 2
    "which can be seen in the browser console." -> the browser also tells you the exception if you look at the request. 500 means an unhandled exception, by the way – Camilo Terevinto Feb 12 '19 at 14:15
  • This could happen for different reasons. As pointed by @CamiloTerevinto, error could be visible in the full response from the browser. Otherwise, just put a `try { } catch (Exception e) { }` to catch the error and gain further details (so you can add them here). – n0idea Feb 12 '19 at 14:20
  • Thanks, error is this, which seems odd since I haven't changed anything in the way I get the entity. Message = "Self referencing loop detected for property 'Matratt' with type 'TomasosPizzeria.Models.Entities.Matratt'. Path 'Products[0].MatrattProdukt[0]'." – Ronnehag Feb 12 '19 at 14:24

1 Answers1

0

When I requested the object from the service class I used a general method to get the navigation objects as well, which in this case seems to have been the cause for the self referencing error.

return await _context.Matratt
            .Include(m => m.MatrattProdukt)
            .ThenInclude(p => p.Produkt)
            .FirstOrDefaultAsync(m => m.MatrattId == id);

Changed to only

 return await _context.Matratt.FirstOrDefaultAsync(p => p.MatrattId == id);

Which is the only thing really needed for the cart.

Ronnehag
  • 29
  • 1
  • 4