Nullable<Datetime> 01/01/0001

Asked

Viewed 371 times

-1

I have a Model field

[Column("sdt_dataPagamento")]
[Display(Name = "Dt. Pagamento")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? DataPagamento { get; set; }

I’m showing in the View this field however the values null become like 01/01/0001

How have I tried to solve this problem.

@if (item.DataPagamento.HasValue)
{
    item.DataPagamento.Value.ToShortDateString();
    <span>teste</span>
}

The teste appears but the date does not.

If I do so:

  @Html.DisplayFor(modelItem => item.DataPagamento)

Appears in format 2016-04-12 (aaaa-mm-dd)

I also tried to

@if(item.DataPagamento.Value.Year != 0001
@if(item.DataPagamento != null)
@if(item.DataPagamento != DateTime.MinValue)
//entre outras tentativas

I want to display only the Date dd/mm/yyyy

I would not like to modify the attributes of the model because it could present errors in other views, I know it is not the correct to display model in the view, I should create a Viewmodel, but in practice I end up doing it when 'I think' it is simple. I would only modify Model if it’s really wrong and it’s the only way.

1 answer

3


Lacked a @ here:

@if (item.DataPagamento.HasValue)
{
    @item.DataPagamento.Value.ToShortDateString();
    <span>teste</span>
}
  • there is some better way or have to do that if?

  • 2

    If you are using C# 6 -> item.DataPagamento?.ToShortDateString() ?? "". If you are using a previous version -> item.DataPagamento.HasValue ? item.DataPagamento.Value.ToShortDateString() : ""

Browser other questions tagged

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