null check returns reference error

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" />
}

My controller is meant to include E update data across the same view. If it is a data refresh, the input="hidden" name idTransacao is included on the page. This insertion occurs when Model is not null, as shown in the controller (the object reference is only created if the value of the idTransacao parameter is given 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 template to the view is null, where is the error?

    
asked by anonymous 14.05.2014 / 20:40

2 answers

2

James, I would trade 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 to put would be in the% caller%, the instantiation of your Action :

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

    return View(transacao ?? new Transacao());
}
    
14.05.2014 / 23:34
2

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

var transacao = new Transacao();

And, in the validation of the view, verify 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 .

    
14.05.2014 / 20:40