The SQL database is storing data with a timestamp of January 1st, 0001 at 12:00:00 AM

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.

https://i.sstatic.net/uTjIO.png

Answer №1

In your Employee model, there is a property called LastUpdated, but you are passing LastChanged from the javascript.

To fix this issue, update the LastChanged property of the post object to LastUpdated.

Modify your createEmployee() function as shown below:

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(),
            LastUpdated: $('#last_changed').val()  // Updated property name
        };

        return employee;
    } catch (e) {
        console.error(e);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing Readability of Public Static Member Variables in Typescript

In my node application, I am utilizing typescript and winston for logging purposes. One key element of my setup is the "Logger" class which consists of a "logger" member and an "init()" function. By exporting this class, I understand that the "logger" memb ...

TypeScript: Extending a Generic Type with a Class

Although it may seem generic, I am eager to create a class that inherits all props and prototypes from a generic type in this way: class CustomExtend<T> extends T { constructor(data: T) { // finding a workaround to distinguish these two ...

There seems to be an issue with ChangepasswordAsync's functionality

When using this code in the admin panel to change a customer's password by a manager, I encountered an issue where the password was not being changed. I obtained the code from here. [HttpPost] [ValidateAntiForgeryToken] public virtual Action ...

Clicking the button in Angular should trigger a series of functions to be

It seems like I'm struggling with a simple question due to my lack of experience in this area. Any guidance or help would be greatly appreciated. I have a button that should trigger multiple functions when clicked, all defined in the same ts file. Wh ...

Begin a new session in ASP.NET using C# and JSON

I am currently facing an issue in my ASP.NET C# project where I need to execute a Json by clicking on a tag, but this action ends the session. To resolve this, I have to call the method RestartSesion(). The code for this is located in the MasterPage. Howe ...

Which one should I prioritize learning first - AngularJS or Laravel?

As a novice web developer, I am embarking on my first journey into the world of frameworks. After much consideration, I have narrowed it down to two options: AngularJS and Laravel. Can you offer any advice on which one would be best for me to start with? ...

Switch up row values in an array and transform them into an object using SheetJS

I am struggling to format an array where each "Working Day" is represented as an object with specific details like index and start/end date. I need help manipulating the JSON data to achieve the desired structure. The package I'm currently using is: ...

What advantages does using a normalized username in Asp.Net Core offer for users seeking faster search results?

My investigation revealed that out of 100,000 users in Asp.Net, searching with NormalizedUserName is quicker compared to searching with UserName. await _context.Users.Where(u => u.NormalizedUserName == username).FirstOrDefaultAsync(); await _context.U ...

TypeScript's type inference feature functions well in scenario one but encounters an error in a different situation

I recently tried out TypeScript's type inference feature, where we don't specify variable types like number, string, or boolean and let TypeScript figure it out during initialization or assignment. However, I encountered some confusion in its be ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Intellisense in VS Code is failing to provide assistance for data within Vue single file components

I am working with a simple code snippet like this https://i.sstatic.net/JSEWJ.png However, within the method, the variable 'name' is being recognized as type any. Interestingly, when I hover over 'name' in the data, it shows up as a s ...

The Alert dialog in Shadcn will automatically close upon clicking the trigger from the dropdown menu

It seems like other people have encountered this issue, but they all used the alert dialog in the same file. I attempted to open the alert dialog using "" and included a dropdownmenuitem with 'delete' inside it. However, when trying to open the ...

What is the best way to pass a state within a route component in react-router?

... import { useNavigate, NavigateFunction } from "react-router"; ... function Form(): JSX.Element { const navigateToCountry = (country: string) => { // Code to navigate to country page with the given country } const [selectedCount ...

$routeProvider fails to catch all cases initially

Recently, I've started working with Angular and I'm facing a problem with my routes. I'm building an Angular SPA with .NET MVC, and although the views are rendering, I've noticed that there are two footers appearing on the page, which l ...

CrossDomain.xml file usage with WCF and Silverlight

Sorry if this question has been asked previously (I searched but couldn't find an answer), I have developed a WCF Service Application and am attempting to access it from my Silverlight 4 app. I have added the service reference to the Silverlight App a ...

Linq-to-SQL struggles to update alterations made in a specific stored procedure

While utilizing linq-to-SQL, I made the decision to expose a variety of stored procedures. However, after some time it became apparent that an additional column was needed in the returned results. To address this, I modified the procedures, removed them fr ...

Exploring the various methods of setting up a Create React App project with TypeScript

One of my old books from a year ago mentioned... npx create-react-app XXX --typescript But looking at the current Create React App documentation, it says... npx create-react-app XXX --template typescript They both seem to yield the same result. Is ther ...

Transforming intricate XML data into JSON format

My XML data structure looks like this: <job> <properties> <name>jobid</name> <value>81963</value> </properties> <properties> ...

Issues with Newtonsoft's C# Custom JsonConverter failing to deserialize a byte array

I'm currently working on developing a custom JsonConverter that aims to serialize byte arrays as an array of numbers instead of the default base 64 string. However, I've encountered a JsonSerializationException while implementing this feature. B ...

Exploring Composite Types with TypeScript's `infer` Keyword

After implementing redux in my project, I found myself including the following code snippet in my store: type CombinedParamTypes<T extends { [key: string]: (state: any, action: any) => any; }> = T extends { [key: string]: (state: infer R, ...