0

Getting null exception trying to add product in to cart

In the code portion below, when I run the project, it seems to work normally, but when I try to add a product to the cart, it throws the exception. I'm getting really stressed out ... I'm about to leave this.

@model Produto
@{
    <div class="card text-right" style="width: 20rem;">
        <div class="card-body">
            <h4 class="card-title">@Model.Nome</h4>
            <h3 class="card-title">@Model.Preco.ToString("c")</h3>
        </div>
        <form id="@Model.ProdutoID" asp-action="AddPCarrinho"
              asp-controller="Carrinho" method="post">
            <input type="hidden" asp-for="ProdutoID" />
            <input type="hidden" name="returnUrl"
                        value="@ViewContext.HttpContext.Request.PathAndQuery()" />
            <span class="card-text p-1">
                @Model.Descricao
                <button type="submit" class="btn btn-success btn-sm pull-right" style="float:right">
                    Add to Cart
                </button>
            </span>
        </form>
    </div>
}

This is the controller

public class CarrinhoController : Controller
{
    private IProdutoRepositorio repositorio;

    public CarrinhoController(IProdutoRepositorio repo)
    {
        repositorio = repo;
    }
    public ViewResult Index(string returnUrl)
    {
        return View(new CarrinhoIndexViewModel
        {
            Carrinho = GetCarrinho(),
            ReturnUrl = returnUrl
        });
    }

    public RedirectToActionResult AddPCarrinho(Guid produtId, string returnUrl)
    {
        Produto produto = repositorio.All
            .FirstOrDefault(p => p.ProdutoID == produtId);

        if (produtId != null)
        {
            Carrinho carrinho = GetCarrinho();
            carrinho.AddItem(produto, 1);
            SalvarCarrinho(carrinho);
        }
        return RedirectToAction("Index", new { returnUrl });
    }

}

This is the ViewModel

namespace SportsStore.Models.ViewModels{
        public class CarrinhoIndexViewModel{
            public Carrinho Carrinho { get; set; }
            public string ReturnUrl { get; set; }
        }
    }

This is the class where i'm getting the exception null reference

public class Carrinho{
        private List<CartLine> lineCollection = new List<CartLine>();

        public virtual void AddItem(Produto produto, int quantidade){
            CartLine line = lineCollection
                .Where(p => p.Produto.ProdutoID == produto.ProdutoID)
                .FirstOrDefault();


            if (line == null)
            {
                lineCollection.Add(new CartLine
                {
                    Produto = produto,
                    Quantidade = quantidade
                });
            }
            else
            {
                line.Quantidade += quantidade;
            }
        }

json.net class

public static class SessionExtensions
    {
        public static void SetJson(this ISession sessao, string key, object value)
        {
            sessao.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T GetJson<T>(this ISession sessao, string key)
        {
            var sessaoData = sessao.GetString(key);
            return sessaoData == null
                ? default(T) : JsonConvert.DeserializeObject<T>(sessaoData);
        }
    }
gcores
  • 11,553
  • 1
  • 44
  • 38
mr.cinza
  • 105
  • 5
  • 2
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Camilo Terevinto May 22 '18 at 22:07
  • @CamiloTerevinto My question is different, and this does not answer – mr.cinza May 22 '18 at 22:24
  • Your question of course it is different, the solution is the same. – Camilo Terevinto May 22 '18 at 22:30
  • Until you provide the stack trace or specifically which line or variable causes the error, it seems appropriate for Camilo to refer you to how to fix the problem generally. Also answers usually come from the answer section, not comments. – GantTheWanderer May 22 '18 at 22:34
  • “Possible duplicate” means the **answer** is a duplicate, not the question. – Dour High Arch May 23 '18 at 00:00

1 Answers1

-1

In the controller, change the line

if (produtId != null)

to

if (produto != null)

As It stands, you are not checking that you are getting something from the repository.

gcores
  • 11,553
  • 1
  • 44
  • 38