C
C#6mo ago
Sk

✅ Trying to make a shopping cart in ASP.Net MVC core problem.

Im trying to access "Cart.CartAmount" in my view, so when "Add to cart" is pressed it will increment "Cart.CartAmount" and that will be shown in the cart in the top right. This is my relevant code, any ideas as to why its not working would be very useful.
No description
No description
No description
23 Replies
Sk
Sk6mo ago
I tried asking chatgpt but i think it messed it up a bit more haha when i hover over the error it just says "An object reference is required for the non-static field, method, or property 'Cart.CartAmount' "
Saber
Saber6mo ago
do you know what that means?
Angius
Angius6mo ago
The data you pass to the view is in the @Model variable Not @Cart
Sk
Sk6mo ago
says "Object reference not set to an instance of an object.'", but it should be set to 5
No description
Angius
Angius6mo ago
No description
Angius
Angius6mo ago
Do you use @Model? @Model.CartAmount?
Sk
Sk6mo ago
yeah
No description
Angius
Angius6mo ago
And it happens straight away, on the first GET request to index?
Sk
Sk6mo ago
wdym?
Angius
Angius6mo ago
Exactly what I said. Does it happen the first time you open the page in the browser, or only after a form submit or something?
Sk
Sk6mo ago
yeah, the second i run it, i dont submit anything
Angius
Angius6mo ago
Odd... Do you have the @model directive properly in the view? That is, @model Cart?
Sk
Sk6mo ago
yeah
No description
Angius
Angius6mo ago
Huh... And are you sure that it's this controller action that gets hit? Place a breakpoint there, run the debugger, see if it gets hit Seeing how it's Views/Shop/Index.cshtml it would be served by ShopController But your code is in CartController
Sk
Sk6mo ago
where abouts?
Angius
Angius6mo ago
Wherever inside of here
No description
Sk
Sk6mo ago
its because i was initally going to direct it to a different view once you press the cart but i got sidetracked trying to get it to show the amount of things currently in the cart it skips over, goes straight to the @Model.CartAmount error
Angius
Angius6mo ago
So, my theory is correct ShopController is what handles the Shop views If you want Shop/Index.cshtml to have data, that data must be returned to the view in ShopController.Index() method
Sk
Sk6mo ago
how would be best to do that?
Angius
Angius6mo ago
Uh
Sk
Sk6mo ago
sorry if these are stupid questions, im still new to asp.net
Angius
Angius6mo ago
Like you are doing right now...? Just in a different place
Sk
Sk6mo ago
thank you! got it working, sorry for the dumb questions