Null check returns reference error

Asked

Viewed 1,040 times

2

Model

public class Transacao
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    public DateTime Data { get; set; }

    [Required]
    public decimal Valor { get; set; }
}

Controller

public ActionResult ManterTransacao(int idTransacao = 0)
{
    (...)

    Transacao transacao = null;

    if (idTransacao > 0)
    {
        transacao = new DaoTransacao().DadosTransacao(idTransacao);
    }
}

View

@model Web.Models.Transacao

(...)

if (Model != null)
{
    <input type="hidden" name="idTransacao" value="@Model.ID" />
}

Man controller serves to include And update data through the same view. If it is a data update, the input="hidden" by name idTransacao is included on the page. This insertion occurs when Model is not null, as shown in the controller (the object reference is created only if the parameter value idTransacao is supplied and is greater than 0).

However, this validation fails:

Object Reference not set to an instance of an Object.

Since the object passed as a view model is null, where is the error?

2 answers

2

The error is in the way the model instantiation is occurring. In our controller, we must create an empty reference in the variable transacao:

var transacao = new Transacao();

And, in view validation, check that the ID is greater than zero (since it is a IDENTITY:

if (Model.ID > 0) // Se for uma referência vazia, o valor será 0
{
    <input type="hidden" name="idTransacao" value="@Model.ID" />
}

Simply assign null to transacao does not work, because the view expects an object of type Transacao.

2


James, I would exchange this code:

if (Model.ID > 0) // Se for uma referência vazia, o valor será 0
{
    <input type="hidden" name="idTransacao" value="@Model.ID" />
}

For this:

@Html.Hidden("idTransacao", Model.ID)

Another thing that would be performative would put on Action caller, the instantiation of its Transacao:

public ActionResult EditarTransacao(int idTransacao = 0)
{
    (...)

    return View(transacao ?? new Transacao());
}
  • 1

    Great Gypsy! As always, irreproachable in the placements.

Browser other questions tagged

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