0

Hi I'm getting a scary problem The controller is invoked normally, the foreach loop works fine, call the view with a List return and the @foreach start the loop and load the registers brought from the DB, but in the last interaction it brokes.

I tried to do with viewdata, viewbag, IEnumerable, List, IList every possibilities but nothing. Is somebody have any spirit and glourious solution? Thanks a lot. The variable names it´s in portuguese, but I keeped the main names like dbcontext in ingles or the standar initials.

Server Error in Application '/'. Object reference not set to an instance of an object.enter image description here Exception Details: System.NullReferenceException: Object reference not defined for an instance of an object.

----> Controller
List<Carrinho_Compras> lstCarrinho = new List<Carrinho_Compras>();
                string idUsuario = Session["ID_Usuario"].ToString();
                var itensCarrinho = db.CarrinhoCompras.Where(x => x.ID_Usuario == idUsuario).ToList();

                if (idUsuario == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }

                if (itensCarrinho == null)
                {
                    return HttpNotFound();
                }

                if (itensCarrinho != null)
                {
                    ViewData["Qtd_Itens"] = itensCarrinho.Count;
                    decimal precoProduto = 0;
                    decimal total = 0;
                    foreach (var item in itensCarrinho)
                    {
                        Carrinho_Compras entCarrinho = new Carrinho_Compras();
                        entCarrinho.ID_Carrinho_Compras = item.ID_Carrinho_Compras;
                        entCarrinho.ID_Cadastro_Prod_Loja = item.ID_Cadastro_Prod_Loja;
                        entCarrinho.ID_Usuario = idUsuario;
                        entCarrinho.Nome_Produto = item.Nome_Produto;
                        entCarrinho.Modelo_Produto = item.Modelo_Produto;
                        entCarrinho.Preco_Produto = item.Preco_Produto;
                        entCarrinho.Quantidade_Produto = item.Quantidade_Produto;
                        entCarrinho.Descricao_Produto = item.Descricao_Produto;
                        entCarrinho.Caminho_Arquivo = item.Caminho_Arquivo;
                        precoProduto = item.Preco_Produto;
                        total = total + precoProduto;
                        entCarrinho.Total = total;

                        lstCarrinho.Add(entCarrinho);
                    }

                    ViewData["Total"] = total;
                    ViewData["CarrinhoCompras"] = lstCarrinho;
                    this.page.Session.Add("Total", total);

                    return View(lstCarrinho);

---> View
@model List<VitrineVirtual.Model.Carrinho_Compras>
<table class="table shoping-cart-table">
                        <tbody>
                            @{
                                var lstCarrinho = ViewData["CarrinhoCompras"] as List<VitrineVirtual.Model.Carrinho_Compras>;
                                var last = Model.Last();
                                foreach (var item in Model.Where(item => item != null))
                                {
                                    if (item.Equals(last))
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        <tr>
                                            <td width="120">
                                                <div class="cart-product-imitation">
                                                    <a href="#" title="Foto">
                                                        <img style="position:initial" width="90" height="90" src="@Url.Content(item.Caminho_Arquivo)" />
                                                    </a>
                                                </div>
                                            </td>
                                            <td class="desc">
                                                <h3>
                                                    <a href="#" class="text-navy">
                                                        @*<input type="text" id="nomeProduto" name="preco" class="form-control" value="@item.Nome_Produto">*@
                                                        @Html.DisplayFor(modelItem => item.Nome_Produto)
                                                    </a>
                                                </h3>
                                                <h4>
                                                    <a href="#" class="text-navy">
                                                        @*<input type="text" id="modeloProduto" name="preco" class="form-control" value="@item.Modelo_Produto">*@
                                                        @Html.DisplayFor(modelItem => item.Modelo_Produto)
                                                    </a>
                                                </h4>
                                                <p class="small">
                                                    @*<input type="text" id="descricaoProduto" name="preco" class="form-control" value="@item.Descricao_Produto">*@
                                                    @Html.DisplayFor(modelItem => item.Descricao_Produto)
                                                </p>
                                                <h3 class="small">
                                                    @*<input type="text" id="precoProduto" class="form-control" value="@item.Preco_Produto">*@
                                                    @Html.DisplayFor(modelItem => item.Preco_Produto))
                                                </h3>
                                            </td>
                                            <td>
                                                <div class="row">
                                                    <div class="col-sm-3 pull-left">
                                                        <input type="text" id="txtAtualizaPreco" name="preco" class="form-control">
                                                        <input type="hidden" name="preco" id="hdnAtualizaPreco" value="@item.Preco_Produto" />
                                                        @*@Html.TextBoxQtd(Request.Form["QtdProduto"], new { value = item.Preco_Produto }, new { @id = "QtdProduto", @class = "form-control", @type = "number", @text = "1" })*@
                                                    </div>
                                                    <div class="col-sm-4">
                                                        <input type="button" id="btnAtualizaPreco" value="Calcular" class="form-control text-white" style="background-color: #3872a2">
                                                        @*@Html.ActionLink("Atualiza Valor", "AtualizaPreco", "CarrinhoCompras", new { quantidade = Request.Form["QtdProduto"] }, new { @class = "btn btn-info" })*@
                                                    </div>
                                                </div>
                                            </td>
                                            <td width="40">
                                                <div class="m-t-sm">
                                                    <button id="btnExcuiItemcarrinho" class="btn-danger btn btn-xs apaga" value="Excuir"><i class="fa fa-trash"></i></button>
                                                    <input type="hidden" name="itemCarrinho" id="hdnExcluiItemCarrinho" value="@item.ID_Carrinho_Compras" />
                                                </div>
                                            </td>
                                        </tr>
                                    }
                                }

                            }

                        </tbody>
                    </table>

jcn737
  • 1
  • 1
  • Post your `inner exception` message because your current error message is too broad. – Giddy Naya Aug 28 '19 at 00:45
  • 2
    When the error occurs the IDE will show you which line, hover your mouse over the variables and see which one is null. Also a tip when you post large amounts of code you should point out where the error occurs. I'm going to close this as a duplicate - the original answer is the best info you can get to solve the **NRE** error. – Jeremy Thompson Aug 28 '19 at 00:48
  • Giddy the message is : Object reference not set to an instance of an object, but the object is not empty and neither null. – jcn737 Aug 28 '19 at 15:33
  • Jeremy I'll post the image that I got from the debugging time, I have this one in another note. So you will see the pointers [0] and [1] of the list with all parameters full, the foreach run this lines, but after the last interaction on it brokes on the "IN" of the foreach, it never happened and I had never saw something like that. I don't know if it's a config that i changed no intencioned, I really don't know. – jcn737 Aug 28 '19 at 15:38
  • I put a validation for if Model is null don't run the foreach before, but it did't worked because the model is not null, so it's valid and getting into @foreach View – jcn737 Aug 28 '19 at 15:43
  • @jcn737 - try model in the View as `@model VitrineVirtual.Model.Carrinho_Compras` instead of list and loop through the list like: `foreach (var item in Model.lstCarrinho)`. In the controller code, you have to assign the lstCarrinho to the Model's list as well. – Jaggan_j Aug 29 '19 at 15:51
  • @Jaggan_j, I'll try this one and feedback the result. Thanks – jcn737 Aug 29 '19 at 20:11
  • The problem was solved I took tasks: First I include a static class named ForcedString to treat nullable properties. Second I setted to Nullable class all the decimal attributes in this model and the foreach interate yill the last and call the view normally. Thanks for all sugestions. – jcn737 Aug 30 '19 at 12:53

0 Answers0