Working with date/time in ASP.NET Core can be challenging, especially for new users. I have an HTML form with fields that initially appear like this:
https://i.sstatic.net/eTAdQ.png
The code for the Date Joined and Last Changed fields is as follows:
<input class="form-control-sm w-100" id="date_joined" value="@(Employee.DateJoined == DateTime.MinValue ? DateTime.UtcNow : Employee.DateJoined)" autocomplete="off" />
<input class="form-control-sm w-100" id="last_changed" value="@DateTime.Now" readonly="readonly" />
While the Last Changed field is read-only, the user can modify the Date Joined field. However, upon saving, the Last Changed value is incorrectly saved as 1/1/0001 12:00:00 AM
. Here's what happens when the save button is clicked in the controller code:
public IActionResult SaveEmployee(Employee employee) {
try
{
_db.Employees.Add(employee);
_db.SaveChanges();
return Json(new { success = true, message = "Saved Successfully" });
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return Json(new { success = false, message = "Error while saving" });
}
}
The employee data is being handled by TypeScript:
private save() {
try {
const employee = this.createEmployee();
Util.request(this.urlSaveEmployee, 'post', 'json', (response) => {
if (response != null) {
$.notify(response.message);
location.reload();
} else {
$.notify(response.message);
console.error('Failed to get data #T7G985. Please try again.');
}
}, () => { }, employee);
} catch (e) {
console.error(e);
}
}
private createEmployee() {
try {
const employee = {
Firstname: $('#first_name').val(),
Lastname: $('#last_name').val(),
Position: $('#position').val(),
Department: $('#department').val(),
Salary: $('#salary').val(),
DateJoined: $('#date_joined').val(),
LastChanged: $('#last_changed').val()
};
return employee;
} catch (e) {
console.error(e);
}
}
}
Any idea why it is still saving the date as the minimum value of DateTime?
UPDATE
Upon debugging, I noticed that TypeScript is returning the correct value. https://i.sstatic.net/8xG3q.png
However, when employee
is passed to the controller from TypeScript, that's where the incorrect date is being displayed.