Question:
I have a Carro
object and I have a nullable integer type property called AnoInspecao
. When creating, I can create a car object with a null inspection year (without typing anything) and persist in the database normally.
var carro = new Carro()
{
carro.AnoInspecao = null;
carro.Nome = "meuCarro"
}
When editing ( View ), I use the following code:
@Html.TexboxFor(model => model.AnoInspecao)
But it doesn't work, because the Textbox
doesn't accept null, thus generating an Exception
.
How can I handle this?
Answer:
Another way is using the following:
@Html.TextBoxFor(model => model.AnoInspecao, new { Value = "", @type = "number" })
Apart from @type
, this solution works for anything Nullable
.