简体   繁体   中英

How show Empty string in Textbox when Date is NULL

I have a DateTime as this is C#:

public DateTime ShipmentDate { get; set; }

I show the value in textbox

This is in cshml:

        <div class="col-sm-2">
            <label for="ShipmentDate">Shipment Date:</label><br />
            <input type="text" name="ShipmentDate" id="ShipmentDate" disabled="disabled" />
        </div>

And this is in JavaScript:

   $('#ShipmentDate').val($.formatDate(PurchaseOrder.ShipmentDate));

When ShipmentDate is nullable like this:

 public DateTime? ShipmentDate { get; set; }

and the date is empty, it shows some random Date as 1960/12/31 in textbox

When ShipmentDate is not nullable shows the date as: 1/1/0001 in textbox

In both in C# date is Null and when I do console.log shows null in the console. How I can show empty String in textbox when ShipmentDate in Null.

Since PurchaseOrder.ShipmentDate can be null, it is worth handling this case so that the $.formatDate(null) doesn't return an invalid date as noticed.

In Javascript, if a variable is null then is treated as a falsy value. So it only executes the formatDate if the ship is not one of the many falsy values , including null .

const ship = PurchaseOrder.ShipmentDate;
$('#ShipmentDate').val(ship ? $.formatDate(ship) : "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM