Date Format using Html.DisplayFor() in MVC5

前端 未结 4 1951
旧时难觅i
旧时难觅i 2021-01-05 11:20

Referencing the answer in this post I added /Views/Shared/DisplayTemplates and added a partial view called ShortDateTime.cshtml as shown below:

@model System         


        
相关标签:
4条回答
  • 2021-01-05 11:50

    The problem you're experiencing is that you are passing a null value into a non-nullable model. Change the partial view's model to DateTime?. For example:

    @model DateTime?          
    @if (!Model.HasValue)
        {
        <text></text>
    }
    else
    {
        @Model.Value.ToShortDateString()
    }
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-05 11:54

    I guess you should declare the BirthDate property as nullable in model class

    public DateTime? BirthDate{ get; set; }
    

    and you must have declared as

    public DateTime BirthDate{ get; set; }
    

    this will expect a value every time.

    if you set as nullable it will not expect a value.

    0 讨论(0)
  • 2021-01-05 11:56

    Have you tried this?

    @if (modelItem.BirthDate != null) { Html.DisplayFor(modelItem => item.BirthDate, "ShortDateTime") }
    
    0 讨论(0)
  • 2021-01-05 11:57

    By applying the conditional statement ahead of the Html helper, only non null values get passed.

    @if (item.BirthDate != null) { @Html.DisplayFor(modelItem => item.BirthDate , "ShortDateTime")}
    
    0 讨论(0)
提交回复
热议问题