Receive int nullable in Razor (@ Html.TextboxFor)

5

I have a Carro object and I have an integer and nullable property called AnoInspecao . When creating, I can create a car object with the null inspection year (without typing anything) and persist in the database normally.

var carro = new Carro()
{
   carro.AnoInspecao = null;
   carro.Nome = "meuCarro"
}

At the time of editing ( View ), I use the following code:

@Html.TexboxFor(model => model.AnoInspecao)

But it does not work, because Textbox does not accept null, thus generating Exception .

How can I handle this?

    
asked by anonymous 03.12.2015 / 18:44

2 answers

3

Another way is to use the following:

@Html.TextBoxFor(model => model.AnoInspecao, new { Value = "", @type = "number" })

By taking @type , this solution works for everything Nullable .

    
03.12.2015 / 18:58
3

Simple, do not pass null to TextBox .

@Html.TexboxFor(model => model.AnoInspecao ?? "")

or

@Html.TexboxFor(model => model.AnoInspecao != null ? model.AnoInspecao.ToString() : "")

The ?? operator is called null-coalescing . It validates what it has on the left side, and if it is null it causes the value sent to be that which comes from the right side.

Related: What is the meaning of the "??" a>

    
03.12.2015 / 18:49