Generic error Undefined object reference for an object instance

Asked

Viewed 2,823 times

2

I already searched the whole forum and did not find an error that matches mine. If anyone can help me. I am with this error:

Error: Object reference not defined for 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 list:

@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 because I have no recorded records.

  • Welcome @Mario, I advise you to format your code using the "Code Sample" so we can help you :)

  • I tried to format, I think it worked ... waiting for help. Thank you!

  • 1

    We need to know on which line the error occurs.

  • The error occurs here: 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.CATEGORY select new listCategory {&#xA; id = a.ID,&#xA; nome_categoria = a.NOME_CATEGORIA&#xA; };&#xA; ViewData["listacategoria"] = lstcategoria.ToList();&#xA; return View(categ); na chamada da index IEnumerable...

  • @Marioantoniopagnozzi, the null Reference error happens because you try to access some attribute of a null object. Try to put a breakpoint on the line where you are having the problem and go debugging variable to variable to see which one is coming null. I think that’s the only way I can help you :)

2 answers

3

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

The Firstordefault method can return null by sending a null model to the view, however it does not seem to have been the cause of the problem, but it is worth testing to 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 on line 3 of view(). The Renderpartial call does not transfer to Viewdata, hence the problem

You can separate the part of Action that preserves this viewdata in another action and then call Renderaction(), ie create an action for the view and fill the viewdata in it.

or to pass on the viewdata, using one of the techniques described in the answer below https://stackoverflow.com/questions/2117367/pass-viewdata-to-renderpartial

  • 1

    Thanks for your suggestion, it worked. in the controller I created an Actionresult for the form and an Actionresult for the list, in the view I called both by Renderaction, I will post the solution.

1

as @Davi Fiamenghi suggested follows the solution:

Controller got 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 I switched to make better identification) was 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.