Receive null int in Razor (@Html.Textboxfor)

Asked

Viewed 506 times

5

I have an object Carro and I have a whole-type, annulable property called AnoInspecao. When creating, I can create a car object with the year of null inspection (without typing anything) and persist in the bank normally.

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

When it’s time to edit (View), I use the following code:

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

But it doesn’t work, because the Textbox does not accept null, thus generating a Exception.

How can I treat that?

  • It only creates an exception when the AnoInspecao is null, certain?

  • Exactly @jbueno

2 answers

3

Simple, do not pass null to the 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 you have on the left and if it is null makes the value sent be the one coming from the right side.

Related: What is the meaning of the operator "??"

  • The problem is that Anoinspect is an integer. With null-coalescing it would turn into a string, resulting in a data incompatibility.

  • You can go 0 then, or it’s no good?

  • The ?? operator cannot be applied to integers.

  • It does not serve rs. I need to leave the field empty.

  • See the other alternative.

  • Keep giving Exception :(

  • By obvious. I used == instead of !=. Change that that will work

  • I had corrected it. It still didn’t work. It returns the following: Templates can be used only with field access, Property access, single-Dimension array index, or single-Parameter custom indexer Expressions.

  • You tried the Gypsy solution?

  • His solved it. I had to restart VS, it might have bugged something. Thank you so much for helping @jbueno. Abs

Show 5 more comments

3


Another way is by using the following:

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

Apart from the @type, this solution works for everything Nullable.

  • It worked now @Gypsy. I restarted VS and worked beautifully rs. Thank you!

Browser other questions tagged

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