C
C#11mo ago
Sk

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
mg
mg11mo ago
$paste
MODiX
MODiX11mo ago
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!
mg
mg11mo ago
that site allows you to paste and share multiple files
Sk
SkOP11mo ago
ok 1 sec
mg
mg11mo ago
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 beforehand
Sk
SkOP11mo ago
BlazeBin - szjtdkipisxm
A tool for sharing your source code with the world!
mg
mg11mo ago
👍 looks like CartService got cut off though
Sk
SkOP11mo ago
using AddToCartTest.Models;

namespace AddToCartTest.Services
{
public class CartService : ICartService
{
private readonly List<Cart> _cartItems = new List<Cart>();

private readonly List<Cart> _allProducts = new List<Cart>
{
new Cart { Id = 1, Name = "Apple Vision Pro", Price = 3499.0M },
new Cart { Id = 2, Name = "Airpod Max", Price = 599.0M },
new Cart { Id = 3, Name = "Macbook Air M3", Price = 2299.0M },
new Cart { Id = 4, Name = "Mac Pro", Price = 5199.0M },
new Cart { Id = 5, Name = "Pro Display XDR", Price = 1399.0M },
new Cart { Id = 6, Name = "iPhone 15 Pro Max", Price = 899.0M },
new Cart { Id = 7, Name = "iPad Pro", Price = 599.0M },
new Cart { Id = 8, Name = "Apple Watch Series 9", Price = 299.0M },
};



public void AddToCart(Cart product)
{
_cartItems.Add(product);
}

public List<Cart> GetCartItems()
{
return _cartItems.ToList();
}
}/*public void AddToCart(int productId)
{
var productToAdd = _allProducts.FirstOrDefault(p => p.Id == productId);
if (productToAdd != null)
{
_cartItems.Add(productToAdd);
}
}

public List<Cart> GetCartItems()
{
return _cartItems.ToList();
}*/

/*public void AddToCart(Cart product)
{
_cartItems.Add(product);
}

public List<Cart> GetCartItems()
{
return _cartItems;
}*/

}
using AddToCartTest.Models;

namespace AddToCartTest.Services
{
public class CartService : ICartService
{
private readonly List<Cart> _cartItems = new List<Cart>();

private readonly List<Cart> _allProducts = new List<Cart>
{
new Cart { Id = 1, Name = "Apple Vision Pro", Price = 3499.0M },
new Cart { Id = 2, Name = "Airpod Max", Price = 599.0M },
new Cart { Id = 3, Name = "Macbook Air M3", Price = 2299.0M },
new Cart { Id = 4, Name = "Mac Pro", Price = 5199.0M },
new Cart { Id = 5, Name = "Pro Display XDR", Price = 1399.0M },
new Cart { Id = 6, Name = "iPhone 15 Pro Max", Price = 899.0M },
new Cart { Id = 7, Name = "iPad Pro", Price = 599.0M },
new Cart { Id = 8, Name = "Apple Watch Series 9", Price = 299.0M },
};



public void AddToCart(Cart product)
{
_cartItems.Add(product);
}

public List<Cart> GetCartItems()
{
return _cartItems.ToList();
}
}/*public void AddToCart(int productId)
{
var productToAdd = _allProducts.FirstOrDefault(p => p.Id == productId);
if (productToAdd != null)
{
_cartItems.Add(productToAdd);
}
}

public List<Cart> GetCartItems()
{
return _cartItems.ToList();
}*/

/*public void AddToCart(Cart product)
{
_cartItems.Add(product);
}

public List<Cart> GetCartItems()
{
return _cartItems;
}*/

}
this is the full code, i just cut out the commeted bit
mg
mg11mo ago
it's best to just share your code exactly as it is
Sk
SkOP11mo ago
sure, mb
mg
mg11mo ago
because that's the code that's running but anyway, are you sure there are actually elements in _cartItems when you access it?
Sk
SkOP11mo ago
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
mg
mg11mo ago
You can initialize the list with some starting elements just like you do for _allProducts
Sk
SkOP11mo ago
ah okay tyyyyy, ill try that wehn im back ive initialized it but even just trying to test using
public IActionResult AddToCart()
{
// For demonstration purposes, manually add a product to the cart
var productToAdd = new Cart
{
Id = 999, // Choose a unique ID
Quantity = 3,
Price = 99.0M,
Name = "Manually Added Product",
// Add other properties as needed
};

_cartService.AddToCart(productToAdd);

return RedirectToAction("Index");
}
public IActionResult AddToCart()
{
// For demonstration purposes, manually add a product to the cart
var productToAdd = new Cart
{
Id = 999, // Choose a unique ID
Quantity = 3,
Price = 99.0M,
Name = "Manually Added Product",
// Add other properties as needed
};

_cartService.AddToCart(productToAdd);

return RedirectToAction("Index");
}
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
mg
mg11mo ago
what code @Sk oh sorry ok right, but are you actually navigating to /AddToCart? And is CartService a singleton?
Sk
SkOP11mo ago
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
mg
mg11mo ago
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
Sk
SkOP11mo ago
ah, i have it as transient in program.cs?
using AddToCartTest.Data;
using AddToCartTest.Services;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
});
builder.Services.AddTransient<ICartService, CartService>();


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Shop}/{action=Index}/{id?}");

app.UseSession();

app.Run();
using AddToCartTest.Data;
using AddToCartTest.Services;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
});
builder.Services.AddTransient<ICartService, CartService>();


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Shop}/{action=Index}/{id?}");

app.UseSession();

app.Run();
this is my program.cs
mg
mg11mo ago
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
Sk
SkOP11mo ago
which is best to use? for this scenario
mg
mg11mo ago
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 requests
Sk
SkOP11mo ago
YESSSSSSSSS. getting somewhere, tysm for being patient and so helpful, it means alot!
mg
mg11mo ago
of course!
Want results from more Discord servers?
Add your server