Checking if the value of type DateTime is null in view and showing blank if null

后端 未结 4 817
隐瞒了意图╮
隐瞒了意图╮ 2020-12-20 23:46

From my controller I have passed value module to view

    public ActionResult Details(long id, string owner)
    {
        var module = _ownedModuleRepositor         


        
相关标签:
4条回答
  • 2020-12-21 00:10

    Try adding a space:

    <dt>Ownership End Date</dt>
    <dd>
        @if (Model.End != null)
        {
            @Model.End
        }
        else
        {
            @:&nbsp;
        }
    </dd>
    
    0 讨论(0)
  • 2020-12-21 00:23

    Won't a ternary operation work here:

    @(Model.End != null ? Model.End.ToString() : "")
    
    0 讨论(0)
  • 2020-12-21 00:24

    you can use C# null coalescing operator:

    @(Model.End?.ToString("dd/MM/yyyy") ?? "Date is Empty")
    
    0 讨论(0)
  • 2020-12-21 00:32

    recently i had this issue when user inserted null value in date column

    which lead to this error:

    System.InvalidOperationException: Nullable object must have a value

    to solve this instead of DisplayFor just use below code in your view , so if the column value is null it will display Date is Empty

     <td>
    
    @(item.Startdate.HasValue ? item.Startdate.Value.ToString("dd/MM/yyyy") : "Date is Empty")
    
    </td>
    

    further reading this and this for model

    hope helps someone.

    0 讨论(0)
提交回复
热议问题