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

-1

I'm trying to retrieve data from a screen with a specific Id , to later record on another screen, however an error occurs saying:

  

"Object reference not set to an instance of an object."

[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();
}
    
asked by anonymous 23.01.2018 / 19:27

1 answer

1

After this line

var c = new Combustivel();

You need to instantiate a Veiculo on the object c

c.Veiculo = new Veiculo();

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

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

    // Propriedades da classe
}
    
23.01.2018 / 20:12