0
I’m trying to make my application save if it has no value to compare, however you are always going through the comparison, I tried to put an if but still problem, this is the class that makes the comparison between my view and my database.
Controller:
[HttpPost]
public ActionResult Adiciona(RotaModel viewModel)
{
var rotas = ckm.Consulta(viewModel.NumCarroId);
// Aqui busca todas as rotas deste veículo
var maiorRota = rotas.OrderByDescending(r => r.Km).FirstOrDefault();
// Aqui você tem a última rota cadastrada, considerando a regra geral
if (viewModel.Km < maiorRota.Km)
{
ModelState.AddModelError("Km_Atual.Invalido",
"A quilometragem precisa ser maior que a anterior");
}
if (ModelState.IsValid)
{
Rota rota = viewModel.CriaRota();
dao.Adiciona(rota);
//return View();
return RedirectToAction("Index");
}
else
{
ViewBag.Usuarios = usuarioDAO.Lista();
ViewBag.Veiculo = veiculoDAO.Lista();
return View("Form", viewModel);
}
}
When I try to save without any pre-registered value, it appears the following error.
Description: An unhandled Exception occurred During the Execution of the Current web request. Please review the stack trace for more information about the error and Where it originated in the code.
Exception Details: System.Nullreferenceexception: Object Reference not set to an instance of an Object.
It worked, but I’m kind of sorry to ask for one more thing, but could you explain to me what this != null would be and how would you interpret it
– Guilherme Padovam
No problem, the reason of the forum is to ask and I am happy to answer.
null
is a "representation" that my variable does not reference anything. If I try to access something from a variable that references nothing, this exception occurs. Then the interpretation would be: If my mother has something to say.– Gabriel Coletta
I was trying to do so so null I put the 0, and I was creating another if/lse to try to do this, but still it was going wrong, so I get much shorter and easier to understand.
– Guilherme Padovam