What is a Nullreferenceexception and how do I fix it?

Asked

Viewed 115 times

-4

inserir a descrição da imagem aqui

System.Nullreferenceexception Hresult=0x80004003 Message=The object reference was not defined as an instance of an object. Source=App_web_cyyu2ydb Stacktrace: in ASP. _Page_views_vacinacao_index_cshtml.Execute() in D: In Development Projects AR Gestcentros Gestcentros Views Vacinacao Index.cshtml:line 35 in System.Web.Webpages.WebPageBase.Executepagehierarchy() in System.Web.Mvc.WebViewPage.Executepagehierarchy() in System.Web.Webpages.StartPage.Runpage() in System.Web.Webpages.StartPage.Executepagehierarchy() in System.Web.Webpages.WebPageBase.Executepagehierarchy(Webpagecontext pageContext, Textwriter Writer, Webpagerenderingbase startPage) in System.Web.Mvc.RazorView.Renderview(Viewcontext viewContext, Textwriter Writer, Object instance) in System.Web.Mvc.BuildManagerCompiledView.Render(Viewcontext viewContext, Textwriter Writer) in System.Web.Mvc.ViewResultBase.Executeresult(Controllercontext context) in System.Web.Mvc.ControllerActionInvoker.Invokeactionresult(Controllercontext controllerContext, Actionresult actionResult) in System.Web.Mvc.ControllerActionInvoker.Invokeactionresultfilterrecursive(Ilist1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) em System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList1 Filters, Int32 filterIndex, Resultexecutingcontext preContext, Controllercontext controllerContext, Actionresult actionResult)

I intend to return the child’s name with the vaccines already administered. what happens is that it does not return anything to me, because if I call the Id it returns the Id of the Child

 using GestCentros.Models;
using System.Collections.Generic;

namespace GestCentros.ViewModels
{
    public class VacinacaoIndexData
    {
       public IEnumerable<Vacinacao> Vacinacoes { get; set; }
        public IEnumerable<Vacina> Vacinas { get; set; }
        public IEnumerable<Enrollment> Enrollments { get; set; }

    }
}

public ActionResult Index(int? id, int? Idvacina)
{
    var user = db.Users.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();

    if (user == null)
    {
        return RedirectToAction("Index", "Home");
    }    
    var viewModel = new VacinacaoIndexData();    
    viewModel.Vacinacoes = db.Vacinacao
        .Include(v => v.Vacinas)
        .Include(v => v.Crianca)
        .Where(c => c.IdCentro == user.IdCentro);  

    if (id != null)
    {
        ViewBag.IdVacinacao = id.Value;
        viewModel.Vacinas = viewModel.Vacinacoes
            .Single(i => i.IdVacinacao == id.Value).Vacinas;
    }    
    if (Idvacina == null) return View(viewModel);           
        ViewBag.IdVacina = Idvacina.Value;
        // Lazy loading
        viewModel.Enrollments = viewModel.Vacinas.Single(x => x.IdVacina == Idvacina).Enrollments;
    // Explicit loading
    Vacina selectedVacina = viewModel.Vacinas.Single(x => x.IdVacina == Idvacina);    
    db.Entry(selectedVacina).Collection(x => x.Enrollments).Load();

        foreach (var enrollment in selectedVacina.Enrollments)
        {
            db.Entry(enrollment).Reference(x => x.Centro).Load();
        }    
        viewModel.Enrollments = selectedVacina.Enrollments;            

    return View(viewModel);
}



    @model GestCentros.ViewModels.VacinacaoIndexData

@{
    ViewBag.Title = "Index";
}

<h2 class="text-center">Lista de Crianças Vacinadas</h2>

<table class="table">
    <tr>
        <th>Nome</th>
        <th>Data Vacinação</th>
        <th>Vacinas</th>
        <th>Operações</th>
    </tr>

    @foreach (var item in Model.Vacinacoes)
     {
        string selectedRow = "";
        if (item.IdVacinacao == ViewBag.IdVacinacao)
        {
            selectedRow = "success";
        }
        <tr class="@selectedRow">
            <td>
                @Html.DisplayFor(model => item.Crianca.Nome)

            </td>
            <td>
                @item.DataVacina.ToString("dd/MM/yyyy")
            </td>
            <td>
                @{
                    foreach (var vacina in item.Vacinas)
                    {
                        @:  @vacina.Nome <br />
                    }
                }
            </td>
        </tr>
     }
</table>

@if (Model.Vacinas != null)
{
    <h3>Vacinas Ministradas na Campanha</h3>
    <table class="table">
        <tr>
            <th>Operações</th>
            <th>Vacina</th>
        </tr>

        @foreach (var item in Model.Vacinas)
        {
            var selectedRow = "";
            if (item.IdVacina == ViewBag.IdVacina)
            {
                selectedRow = "success";
            }
            <tr class="@selectedRow">
                <td>
                    @Html.ActionLink("Selecionar", "Index", new { IdVacina = item.IdVacina }, new { @class = "btn btn-sm btn-secundary" })
                    | @Html.ActionLink("Voltar a Lista", "Index", new { }, new { @class = "btn btn-sm btn-default" })
                </td>                
                <td>
                    @item.Nome
                </td>
            </tr>
        }

    </table>
}

@if (Model.Enrollments != null)
{
    <h3>
        Students Enrolled in Selected Course
    </h3>
    <table class="table">
        <tr>
            <th>Name</th>
            <th>Grade</th>
        </tr>
        @foreach (var item in Model.Enrollments)
        {
            <tr>
                <td>
                    @item.Centro.Name
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Grade)
                </td>
            </tr>
        }
    </table>
}
  • Manuel, also post the complete error message.

  • 4

    NullReferenceException happens when an object is not instantiated and is trying to use it. See the error line and see which object was not instantiated

  • 1

    Manuel, print doesn’t help! : ) Click on the "copy details" button and post it here. : ) This is important even for new questions. Ricardo’s comment is perfect, the error is quite simple. :)

  • I posted the detail of the error

  • Managed to solve?

  • I haven’t quite figured it out yet

  • I tried harder I couldn’t see the error

  • I had an experience similar to an exercise these days, in my case I’m temporarily on an Ubuntu notebook, using Visual Code and . NET Core, in my situation I had to delete the bin and obj folders and redo the build so that the error would stop and the program would start running again. It was running normally and after some changes stopped and even returning to the previous state it did not run. In my case debug pointed to an error on an empty line just after the opening key of a method { and before the first line of code of the method in question.

Show 3 more comments

2 answers

1

TL;DR:

You are trying to access a variable from an instantiated object. On the line item.Crianca.Nome or the item is null, or the prop Crianca of item is null. Instantiating what is not instantiated solves the problem.

Explanation

There are two types of value for variables: Tipos de valor and Tipos de referência.

A Value Type stores the variable in memory Stack. Examples of Value Type: Int32, bool, double. When vc creates a value type, a memory space is allocated to store the value and the variable stores the value directly.

The Reference Type stores the object in memory Heap and creates in the Stack only a reference to the address of the object in Heap, but not the object directly. Basically a pointer. Example: An object generated from a class

When we create an object (Crianca filho;), is generated in memory Stack a space to store the instance address (in this case, the variable is filled with the address, but the location the address points to is null, as the instance has not yet been created).

When instantiating the object(filho = new Crianca();) a space in memory Heap is allocated to store variable data.

If we attempt to access a property of an object not yet instantiated, the Stack will point to a value that is null, so will have a NullReferenceException

Useful links:

Value type vs Reference type

Difference Heap vs Stack

  • Thank you very much Beast. I’ll take a better look. if you can help me by taking a look at the code, I’d appreciate it

0

As stated in the comments, Exception NullReferenceException occurs when an attempt to access an attribute or method of a non-einstantiated object occurs.

It would occur, for example, when trying to access an attribute after instantiating an object in the form of Objeto instanciaObjeto; instead of Objeto instanciaObjeto = new Objeto();.

From the image that was sent, it seems that the error occurs when accessing an attribute of the Child object. I suggest you check, with a debug, if the object is being loaded normally with the Vaccination.

  • Someone Can Help On Live?

  • Can someone give me a hand on the live?

Browser other questions tagged

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