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; }
} catch (Exception e) { }` to catch the error and gain further details (so you can add them here).– n0idea Feb 12 '19 at 14:20