Error: Undefined object reference for an object instance

Asked

Viewed 832 times

0

I’m trying to rescue data from a screen with a Id specific, to later record on another screen, but an error occurs saying:

"Undefined object reference for an object instance."

[HttpGet]
public ActionResult Registro(int id)
{
        var model = new CombustivelViewModelRegistro();
        try
        {
            var rep = new AtribuirVeiculoRepsitorio();
            AtribuirVeiculo av = rep.ObterPorId(id);
            model.Veiculo = av.Veiculo.Matricula;
            model.Funcionario = av.Funcionario.Nome;
        }
        catch(Exception e)
        { 
            ViewBag.Mensagem = e.Message;
        }           
    return View(model);
}

[HttpPost]
public ActionResult Registro(CombustivelViewModelRegistro model)
{
    if (ModelState.IsValid)
    {
        var c = new Combustivel();
        try
        {
            c.DataAbastecimento = model.DataAbastecimento;  
            c.DataCadastro = DateTime.Now;
            c.Kilomtragem = Convert.ToDouble(model.Kilometragem);
            c.Quantidade = model.Quantidade;
            c.IdCombustivel = model.IdCombustivel;
            c.Veiculo.Matricula = model.Veiculo;
            c.Funcionario.Nome = model.Funcionario;

            var service = new CombustivelRepositorio();
            service.Inserir(c);

            return RedirectToAction("Index");
        }
        catch (Exception e)
        {
            ViewBag.Mensagem = e.Message;
        }
    }
    return View();
}
  • 1

    On what line does it happen? Probably these calls to your repository that searches for a value may be returning a null, and you’re trying to assign a value to a property.

  • Provide more details in your question as a question with the similar title has already been answered and given as closed

  • Your Vehicle is null and you try to assign a value to its License Plate.

  • I must initialize c.Vehicle = new Vehicle(); c.Employee = new Employee();

  • @Maxfxavier You are still receiving the error "Object reference not defined for an instance of an object"?

1 answer

1

After this line

var c = new Combustivel();

You need to instantiate a Veiculo in the object c

c.Veiculo = new Veiculo();

You can also change the constructor of Combustivel for whenever an instance is created, also create an instance of Veiculo.

public class Combustivel
{
    public Combustivel()
    {
        this.Veiculo = new Veiculo();
    }

    // Propriedades da classe
}

Browser other questions tagged

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