✅ 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.
23 Replies
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'
"
do you know what that means?
The data you pass to the view is in the
@Model
variable
Not @Cart
says "Object reference not set to an instance of an object.'", but it should be set to 5
Do you use
@Model
?
@Model.CartAmount
?yeah
And it happens straight away, on the first
GET
request to index?wdym?
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?
yeah, the second i run it, i dont submit anything
Odd... Do you have the
@model
directive properly in the view?
That is, @model Cart
?yeah
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
where abouts?
Wherever inside of here
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
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()
methodhow would be best to do that?
Uh
sorry if these are stupid questions, im still new to asp.net
Like you are doing right now...?
Just in a different place
thank you! got it working, sorry for the dumb questions