trying to make an add to cart application in asp.net mvc core
i have been trying for ages to get it to work and am just trying to test it but i have no idea as to why the information isnt getting shown on the view, will have screenshots posted below
23 Replies
$paste
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
that site allows you to paste and share multiple files
ok 1 sec
but it looks like your issue is that your
CartService.GetCartItems()
returns the _cartItems
field, which you never add anything to
Unless you've accessed the AddToCart
endpoint beforehandBlazeBin - szjtdkipisxm
A tool for sharing your source code with the world!
👍
looks like
CartService
got cut off though
this is the full code, i just cut out the commeted bit
it's best to just share your code exactly as it is
sure, mb
because that's the code that's running
but anyway, are you sure there are actually elements in
_cartItems
when you access it?no, how would be the best way to assign my items in CartServices to _cartItems, at the moment im just trying to test it to make sure its working then i will be able to connect it so when a buttons pressed its added to cart
You can initialize the list with some starting elements just like you do for
_allProducts
ah okay tyyyyy, ill try that wehn im back
ive initialized it but even just trying to test using
I cant get it to work, so im not sure what else to do
because that code should add an item to the cart but it still just displays an empty cart
what code
@Sk
oh sorry
ok right, but are you actually navigating to
/AddToCart
?
And is CartService
a singleton?yeah but it just sends me back to /Cart - like i will put in localhost/Cart/Addtocart and i just get sent bacm to localhost/cart
what do you mean? sorry if thats a stupid question haha
nah not at all. it's not obvious
the way that your controller actually gets an instance of
ICartService
is through a service provider
presumably at some point you wrote services.AddX<ICartService, CartService>()
, right?
where X
is Singleton
, Scoped,
or Transient
ah, i have it as transient
in program.cs?
this is my program.cs
Yeah that'll do it
Those are called service lifetimes
Transient means it creates a new instance of the service every time it's asked for
Scoped is a little different; in this case it's once per request
Singleton is created once for the entire lifetime of the program
which is best to use?
for this scenario
So because you registered it as transient, it's creating one
CartService
when you add to the cart, and then creating an entirely new one when you get the cart items
In this case, singleton
Because you want the state to persist across all the requestsYESSSSSSSSS.
getting somewhere, tysm for being patient and so helpful, it means alot!
of course!