I am injecting two classes in my controller.
In the get request, when I put a break point, I can see there is an instance being retrieved in the constructor .
However in the post action, the instance is null ?
here is my controller class;
using BethanyPieShop.Models;
using Microsoft.AspNetCore.Mvc;
namespace BethanyPieShop.Controllers
{
public class OrderController : Controller
{
public IOrderRepository _orderRepository { get; set; }
public ShoppingCart _shoppingCart { get; set; }
public OrderController(IOrderRepository _orderRepository, ShoppingCart _shoppingCart)
{
_orderRepository = _orderRepository;
_shoppingCart = _shoppingCart;
}
public IActionResult Checkout()
{
return View();
}
[HttpPost]
public IActionResult Checkout(Order order)
{
// Null here _shoppingCart
var items = _shoppingCart.GetShoppingCartItems();
_shoppingCart.ShoppingCartItems = items;
if (_shoppingCart.ShoppingCartItems.Count == 0)
{
ModelState.AddModelError("", "Your cart is empty, add some pies first");
}
if (ModelState.IsValid)
{
_orderRepository.CreateOrder(order);
_shoppingCart.ClearCart();
return RedirectToAction("CheckoutComplete");
}
return View(order);
}
public IActionResult CheckoutComplete()
{
ViewBag.CheckoutCompleteMessage = ", thanks for your order. You'll soon enjoy our delicious pies!";
return View();
}
}
}
I registered the services in the main class:
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<ShoppingCart>();
CodePudding user response:
You are setting a variable with the same name. Without using a 'this.' statement. Try changing the following from
public OrderController(IOrderRepository _orderRepository, ShoppingCart _shoppingCart)
{
_orderRepository = _orderRepository;
_shoppingCart = _shoppingCart;
}
to
public OrderController(IOrderRepository orderRepository, ShoppingCart shoppingCart)
{
_orderRepository = orderRepository;
_shoppingCart = shoppingCart;
}
CodePudding user response:
So I think you should use this. Like this:
public OrderController(IOrderRepository _orderRepository, ShoppingCart _shoppingCart)
{
this._orderRepository = _orderRepository;
this._shoppingCart = _shoppingCart;
}