I have a ViewModel that displays the items in the cart CartItems and one that displays the total cost. My if statement that I currently have doesn't work, why is this and how do i go about fixing it? CartItems is a List. Im trying to make it so that if there is no items in the cart, the message CART EMPTY is displayed
ShoppingCartViewModel viewModel = new ShoppingCartViewModel
{
CartItems = cart.GetCartItems(),
CartTotal = cart.GetTotal()
};
if (viewModel.CartItems == null)
{
ViewBag.CartStatus = "CART EMPTY";
}
else
{
ViewBag.CartStatus = "Cart Has item, proceed";
}
If your method always returns an empty collection you probably want to check against that instead of null
:
if (viewModel.CartItems.Any())
{
ViewBag.CartStatus = "CART EMPTY";
}
else
{
ViewBag.CartStatus = "Cart Has item, proceed";
}
Also this ViewBag
is just horrible. My eyes are bleeding every single time I see it. You've got a view model, why not just have a CartStatus
tring property on it and update it accordingly?