C
C#12mo 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
SkOP12mo 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
Saber12mo ago
do you know what that means?
Angius
Angius12mo ago
The data you pass to the view is in the @Model variable Not @Cart
Sk
SkOP12mo ago
says "Object reference not set to an instance of an object.'", but it should be set to 5
No description
Angius
Angius12mo ago
No description
Angius
Angius12mo ago
Do you use @Model? @Model.CartAmount?
Sk
SkOP12mo ago
yeah
No description
Angius
Angius12mo ago
And it happens straight away, on the first GET request to index?
Sk
SkOP12mo ago
wdym?
Angius
Angius12mo 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
SkOP12mo ago
yeah, the second i run it, i dont submit anything
Angius
Angius12mo ago
Odd... Do you have the @model directive properly in the view? That is, @model Cart?
Sk
SkOP12mo ago
yeah
No description
Angius
Angius12mo 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
SkOP12mo ago
where abouts?
Angius
Angius12mo ago
Wherever inside of here
No description
Sk
SkOP12mo 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
Angius12mo 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
SkOP12mo ago
how would be best to do that?
Angius
Angius12mo ago
Uh
Sk
SkOP12mo ago
sorry if these are stupid questions, im still new to asp.net
Angius
Angius12mo ago
Like you are doing right now...? Just in a different place
Sk
SkOP12mo ago
thank you! got it working, sorry for the dumb questions
Want results from more Discord servers?
Add your server