"Object reference not set to an instance of an object." error when displaying a null value in view

2

Within C # MVC5, I'm creating a user registration form with multiple fields. One of them is the (Gratified) Role field, which the user may or may not have.

The following is the class User:

public class Usuarios
{

    public int Id { get; set; }

    [Required, StringLength(60)]
    public string Nome { get; set; }

    [DisplayName("Matrícula"),StringLength(7)]
    public string Matricula {get;set;}

    [DisplayName("DV"),Required]
    public int MatriculaDV {get;set;}

    [StringLength(20)]
    public string OAB {get;set;}

    [DisplayName("Gênero")]
    public Genero Genero { get; set; } 
    public bool Ativo {get;set;}

    [DisplayName("Data de Nascimento"), DisplayFormat(DataFormatString="{0:d}")]
    public DateTime DataNascimento { get; set; }

    [DisplayName("Unidade")]
    public virtual int? UnidadesID {get;set;}
    public virtual Unidades Unidade {get;set;}

    [DisplayName("Cargo")]
    public virtual int? CargosID { get; set; }
    public virtual Cargos Cargo { get; set; }

    [DisplayName("Função")]
    public virtual int? FuncoesID {get;set;} //eis a funcao
    public virtual Funcoes Funcao {get;set;}

}

And the Functions class:

public class Funcoes
{
    public int Id { get; set; }
    public int Codigo { get; set; }
    [StringLength(70)]
    public string Funcao { get; set; }

    public virtual IList<Usuarios> Usuario { get; set; }
}

The inclusion form allows you to add a new record without a function.

However, when trying to list them, the view that contains the table generates the error below on the line where it tries to show a null function record (line @ user.Function.Function):

  

An exception of type 'System.NullReferenceException' occurred in   App_Web_tneo00cv.dll but was not handled in user code

     

Additional information: Object reference not set to one   instance of an object.

Follow the UserController's Index view:

@model IList<Aplicacoes.Entidades.Usuarios>

@{
    ViewBag.Title = "Usuários";
}
<h4>Lista de Usuários</h4>
<a class="btn btn-primary" href="Usuario/Form">Novo Usuário</a>
<a class="btn btn-default" href="Unidades/Index">Unidades</a>
<a class="btn btn-default" href="Cargo/Index">Cargos</a>
<a class="btn btn-default" href="Funcao/Index">Funções</a>
@*@Html.ActionLink("Novo Usuário", "Form", "Usuario", new { @class="btn btn-primary"})
@Html.ActionLink("Unidades", "Index", "Unidades", new { @class = "btn btn-default" })*@
<table class="table table-striped table-hover">
    <thead>
        <tr>
            <th>Matricula</th>
            <th>DV</th>
            <th>Nome</th>
            <th>Cargo</th>
            <th>Função</th>
            <th>Unidade</th>
            <th>OAB</th>
            <th>Data Nasc.</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var usuario in @Model.OrderBy(usuario => usuario.Nome))
        {
            <tr>
                <td>@usuario.Matricula.ToUpper()</td>
                <td>@usuario.MatriculaDV</td>
                <td>@usuario.Nome.ToUpper()</td>
                <td>@usuario.Cargo.Cargo</td>
                <td>@usuario.Funcao.Funcao</td> //o erro ocorre aqui
                <td>@usuario.Unidade.Sigla</td>
                <td>@usuario.OAB</td>
                <td>@usuario.DataNascimento.ToShortDateString()</td>

            </tr>
        }
    </tbody>
</table>

I tried to work around this way in the View itself, but it did not work:

if(@usuario.Funcao == null)
{
    <td>-</td>
}else{
    <td>@usuario.Funcao.Funcao</td> //o erro acontece aqui novamente
}

Follow the UserController for inquiry:

public class UsuarioController : Controller
{
    // GET: Usuario
    private UsuarioDAO uDao;
    private CargosDAO cDao;
    private FuncoesDAO fDao;
    private UnidadesDAO udDao;

    public UsuarioController(UsuarioDAO uDao, CargosDAO cDao, FuncoesDAO fDao, UnidadesDAO udDao)
    {
        this.uDao = uDao;
        this.cDao = cDao;
        this.fDao = fDao;
        this.udDao = udDao;
    }

    public ActionResult Index()
    {
        IList<Usuarios> usuarios = uDao.Lista();
        return View(usuarios);
    }

    public ActionResult Form()
    {
        ViewBag.Cargos = cDao.Lista().OrderBy(Cargos =>Cargos.Cargo);
        ViewBag.Funcoes = fDao.Lista().OrderBy(Funcoes => Funcoes.Funcao);
        ViewBag.Unidades = udDao.Lista().OrderBy(Unidades => Unidades.Nome);

        return View();
    }

    public ActionResult Adiciona(Usuarios usuario)
    {
        uDao.Adiciona(usuario);
        return RedirectToAction("Index");
    }

    public ActionResult Remove(int id)
    {
        Usuarios usuario = uDao.BuscaPorId(id);
        uDao.Remove(usuario);
        return RedirectToAction("Index");
    }
    public ActionResult Detalhes(int id)
    {
        Usuarios usuario = uDao.BuscaPorId(id);
        return View(usuario);
    }

    public ActionResult Atualiza(Usuarios usuario)
    {
        uDao.Atualiza(usuario);
        return RedirectToAction("Index");

    }

}

I understand that the error prompts me to start the variable before. But I can not figure out where to start this variable, since it is a "class within a class".

    
asked by anonymous 19.02.2016 / 19:37

2 answers

1

Have you tried adding a constructor in the user class?

  public Usuarios()
    {
        this.FuncoesID = 0;
        this.Funcoes = new Funcoes();
    }
    
22.02.2016 / 13:59
0

Can you use the? to print the possible null objects.

   <tbody>
    @foreach (var usuario in @Model.OrderBy(usuario => usuario.Nome))
    {
        <tr>
            <td>@usuario.Matricula?.ToUpper()</td>
            <td>@usuario.MatriculaDV</td>
            <td>@usuario.Nome.ToUpper()</td>
            <td>@usuario.Cargo?.Cargo</td>
            <td>@usuario.Funcao?.Funcao</td> //o erro ocorre aqui
            <td>@usuario.Unidade?.Sigla</td>
            <td>@usuario.OAB</td>
            <td>@usuario.DataNascimento?.ToShortDateString()</td>

        </tr>
    }
</tbody>
    
12.06.2018 / 16:14