Generic error Object reference not set to an instance of an object

2

I've looked all over the forum and I did not find an error that matches mine. If anyone can help me. I'm having this error:

  

Error: Object reference not set to an instance of a   object.

Linha 1:  @model MimoLacosAdm.Models.CATEGORIA
Linha 2:  @{
Linha 3:      IEnumerable<MimoLacosAdm.Models.listaCategoria> listaCategoria = (IEnumerable<MimoLacosAdm.Models.listaCategoria>)ViewData["listacategoria"];
Linha 4:      
Linha 5:  }

Model:

namespace MimoLacosAdm.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

public partial class CATEGORIA
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public CATEGORIA()
    {
        this.PRODUTO = new HashSet<PRODUTO>();
    }

    [Key]
    [Display(Name="Código")]
    public int ID { get; set; }

    [Required(ErrorMessage="Categoria deve ser informada")]
    [Display(Name="Categoria")]
    public string NOME_CATEGORIA { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<PRODUTO> PRODUTO { get; set; }
}

public class listaCategoria
{
    public int? id { get; set; }
    public string nome_categoria { get; set; }
}
}

Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MimoLacosAdm.Models;

namespace MimoLacosAdm.Controllers
{

public class CategoriaController : Controller
{
    //
    // GET: /Categoria/
    private mimolacosadmEntities db = new mimolacosadmEntities();

    public ActionResult Index()
    {
        ViewBag.Action = string.Empty;
        db.Database.Connection.Open();
        var categ = db.CATEGORIA.Where(a => a.ID.Equals(0)).FirstOrDefault();
        var lstcategoria = from a in db.CATEGORIA
                           select new listaCategoria
                           {
                               id = a.ID,
                               nome_categoria = a.NOME_CATEGORIA
                           };
        ViewData["listacategoria"] = lstcategoria.ToList();
        return View(categ);

    }
    public List<listaCategoria> CarregaGrid(int? id)
    {

            if (id != null || id > 0)
            {
                return (from a in db.CATEGORIA
                            where a.ID == id
                            select new listaCategoria
                            {
                                id = a.ID,
                                nome_categoria = a.NOME_CATEGORIA
                            }).AsParallel().ToList();

            }
            else
            {
                return (from a in db.CATEGORIA                                
                            select new listaCategoria
                            {
                                id = a.ID,
                                nome_categoria = a.NOME_CATEGORIA
                            }).AsParallel().ToList();
            }
    }
}
}

View Index:

@model MimoLacosAdm.Models.CATEGORIA
@{
    IEnumerable<MimoLacosAdm.Models.listaCategoria> listaCategoria = (IEnumerable<MimoLacosAdm.Models.listaCategoria>)ViewData["listacategoria"];

}
<p><b>Categorias</b></p>
<hr />
<div id="cadastro">
    <fieldset>
        <legend>Cadastro</legend>

            <ul style="list-style:none;display:inline-table">
                <li>
                    <a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#corposite" href="@Url.Action("Incluir","Categoria")" role="button"><img src="/Contents/Images/btnAdd.png" /></a>
                </li>
                <li>
                    <a class="btnIncluir" data-ajax="true" data-ajax-mode="replace" data-ajax-update="#corposite" href="@Url.Action("Delete", "Categoria", new { id = Model.ID})" role="button"><img src="/Contents/Images/btnExcluir.png" /></a>
                </li>
            </ul>

        @{Html.RenderPartial("formCategoria", Model); }
    </fieldset>
</div>
<div id="Grid">
    <fieldset>
        <legend>Lista Categoria</legend>
            @{Html.RenderPartial("listaCategoria", listaCategoria);}       
    </fieldset>
</div>

View formCategory:

@model  MimoLacosAdm.Models.CATEGORIA

@using (Ajax.BeginForm((string)ViewBag.Action, "Categoria", new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "conteudo-cadastro"
}))
{
    @Html.AntiForgeryToken();
    @Html.ValidationSummary(true)

    <ul style="list-style:none;float:left">
        <li>@Html.Raw(ViewBag.Message)</li>
        <li>@Html.LabelFor(a => a.ID)</li>
        <li>@Html.TextBoxFor(a => a.ID, new { @readonly="true" })</li>
    </ul>
    <ul style="list-style:none;float:left">
        <li>@Html.LabelFor(a => a.NOME_CATEGORIA)</li>
        <li>@Html.ValidationMessageFor(a => a.NOME_CATEGORIA)</li>
        <li>@Html.TextBoxFor(a => a.NOME_CATEGORIA, new { @size="50px" }</li>
    </ul>
    <ul style="list-style:none;float:left;clear:both;display:inline-table">        
        <li><button type="submit" value="Gravar" style="border: none">Gravar</button></li>
        <li><button type="reset" value="Cancelar" style="border:none">Cancelar</button></li>
    </ul>
}

View listCategory:

@model IEnumerable<MimoLacosAdm.Models.listaCategoria>
@{
    IEnumerable<MimoLacosAdm.Models.listaCategoria> listaCategoria = (IEnumerable<MimoLacosAdm.Models.listaCategoria>)ViewData["listacategoria"];
    var grid = new WebGrid(source: listaCategoria.ToList(), canPage: true, ajaxUpdateCallback: "conteudo-cadastro", ajaxUpdateContainerId: "Grid", defaultSort: "nome_categoria", rowsPerPage: 10);
}

@grid.GetHtml(tableStyle: "grid", alternatingRowStyle: "alternate", headerStyle: "header", columns: new[] {
    grid.Column(columnName: "id", header: "Código",format: a => new HtmlString(Ajax.ActionLink((string)a.id.ToString(),"Detalhe",new { id = a.id },new AjaxOptions { UpdateTargetId = "conteudo-cadastro" }).ToString()),canSort: true),
    grid.Column(columnName: "nome_categoria", header: "Nome",format: a => new HtmlString(Ajax.ActionLink((string)a.nome_categoria.ToString(),"Detalhe",new { id = a.id },new AjaxOptions { UpdateTargetId = "conteudo-cadastro" }).ToString()),canSort: true)
})

Database: SQLServer

The table is empty, as I do not have any records yet.

    
asked by anonymous 18.11.2016 / 15:18

2 answers

3

This error occurs when trying to reference a member of a (variable) object that is null.

The FirstOrDefault method can return null, sending a null model to the view, however this does not seem to be the cause of the problem, but it is worth testing replace with a new Categoria()

var categ = db.CATEGORIA.Where(a => a.ID.Equals(0)).FirstOrDefault();

As you said, the error occurs when accessing viewdata, line 3 of view (). The RenderPartial call does not pass the ViewData, hence the problem

You can separate the part of the Action that previews this viewdata into another action and then call RenderAction (), that is, create an action for the view and populate the viewdata in it.

or go through the viewdata using one of the techniques described in the answer below link

    
18.11.2016 / 16:58
1

As the @Davi Fiamenghi suggested follows the solution:

Controller stayed like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MimoLacosAdm.Models;

namespace MimoLacosAdm.Controllers
{
    public class CategoriaController : Controller
    {
        //
        // GET: /Categoria/
        private mimolacosadmEntities db = new mimolacosadmEntities();

        public ActionResult Categoria()
        {
            ViewBag.Action = string.Empty;                        
            return View();

        }
        public ActionResult FormCategoria()
        {            
            return PartialView("formCategoria");
        }
        public ActionResult ListaCategoria()
        {
            ViewData["listacategoria"] = CarregaGrid(null).ToList();
            return PartialView("listaCategoria");
        }
        public List<listaCategoria> CarregaGrid(int? id)
        {

                if (id != null || id > 0)
                {
                    return (from a in db.CATEGORIA
                                where a.ID == id
                                select new listaCategoria
                                {
                                    id = a.ID,
                                    nome_categoria = a.NOME_CATEGORIA
                                }).AsParallel().ToList();

                }
                else
                {
                    return (from a in db.CATEGORIA                                
                                select new listaCategoria
                                {
                                    id = a.ID,
                                    nome_categoria = a.NOME_CATEGORIA
                                }).AsParallel().ToList();

                }

        }

    }
}

and my View Category (old saw index that I changed to get better identification) looks like this:

<p><b>Categorias</b></p>
<hr />
<div id="cadastro">
    <fieldset>
        <legend>Cadastro</legend>

            <ul style="list-style:none;display:inline-table">
                <li>
                    <a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#corposite" href="@Url.Action("Incluir","Categoria")" role="button"><img src="/Contents/Images/btnAdd.png" /></a>
                </li>                
            </ul>

        @{Html.RenderAction("FormCategoria", "Categoria"); }
    </fieldset>
</div>
<div id="Grid">
    <fieldset>
        <legend>Lista Categoria</legend>
            @{Html.RenderAction("ListaCategoria", "Categoria");}       
    </fieldset>
</div>
    
18.11.2016 / 17:31