简体   繁体   中英

dotnet core 2 Web C# Object reference not set to an instance of an object?

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);
        }
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM