Data is being fetched successfully but is not being saved or updated in ASP.NET Core 3.1

My issue is reminiscent of a similar inquiry on this post. Despite implementing the suggested solutions, my problem persists as I opted for a slightly different approach in terms of storing data in the database.

Employee Model Class

    public class Employee
    {
        [Key]
        public int EmployeeId { get; set; }

        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
}

Type script code related to saving

private urlSaveEmployee = '/employee/save';

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 = {
                EmployeeId: $('#employee_id').val(),
                Firstname: $('#first_name').val(),
                Lastname: $('#last_name').val()
            };
            return employee;
        } catch (e) {
            console.error(e);
        }
    }

Save button View code

<tr>
                <td style="width: 100px">First Name*</td>
                <td>
                    <input type="hidden" id="employee_id" value="@Employee.EmployeeId" />
                    <input class="form-control-sm w-100" id="first_name" value="@Employee.FirstName" autocomplete="off" />
                </td>
            </tr>
            <tr>
                <td style="width: 100px">Last Name*</td>
                <td>
                    <input class="form-control-sm w-100" id="last_name" value="@Employee.LastName" autocomplete="off" />
                </td>
            </tr>


<button type="button" class="btn btn-sm btn-outline-primary employee-form-save" id="save_form">
                        <i class="fa fa-floppy-o" style="margin-right:5px"></i>
                        Save
                    </button>

Controller code related to Save

        [HttpPost("employee/save")]
        public async Task<IActionResult> SaveEmployee(Employee employee) {
            try
            {
                Employee employeeFromDb = await _db.Employees.FirstOrDefaultAsync(e => e.EmployeeId == employee.EmployeeId);

                if (employeeFromDb == null)
                {
                    _db.Employees.Add(employee);
                    _db.SaveChanges();
                    return Json(new { success = true, message = "Saved Successfully" });
                } else {
                    _db.Employees.Update(employee);
                    _db.SaveChanges();
                    return Json(new { success = true, message = "Updated Successfully" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Json(new { success = false, message = "Error while saving" });
            }
        }

Upon clicking the save button, the page reloads without any modifications taking effect. Setting breakpoints revealed that the employeeFromDb enters the .Update condition, yet the page merely refreshes and the database remains unchanged. Refer to this screenshot captured at the breakpoint: https://i.sstatic.net/sltit.png

Answer №1

Great to hear that it was successful, just a simple test. The information you discovered about EntityState is vital for your understanding, and I recommend continuing with this helpful tutorial - https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-3.1

Understanding Entity States The database context monitors whether entities in memory are synchronized with their corresponding rows in the database, influencing the outcome of SaveChanges method calls. For instance, when a new entity is added using the Add method, its state is marked as Added. Upon calling SaveChanges, an SQL INSERT command is executed by the database context.

In the Edit example where Bind properties are passed alongside the record's Id parameter, that could serve as a better reference for your task. Alternatively, creating a mapper class to transform your request object into an Entity Framework object for proper updates might also be effective. It's possible that you may have overlooked an exception earlier if your breakpoint wasn't set within that code block.

Additionally, utilizing binding through Ajax json calls can be advantageous -

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

Make decisions on which column headers to exclude or include in the Select statement in Oracle SQL based on specific conditions

I am dealing with a table that has the following schema: Documentno created docstatus 498461 08-OCT-14 IN 501681 27-OCT-14 IN 544491 19-AUG-15 IP 550041 28-SEP-15 IP The desired output format should be as follows: S ...

Issue encountered when attempting to access IIS using a C# service

When I call the code below from a Windows service written in C#: try { ServerManager m = new ServerManager(); if(m != null) { SiteCollection sites = m.Sites; //An exception occurs here } } catch (Exception ex) { } I e ...

Tips for streamlining batched SQL inserts with an excessive number of parameters

I am currently facing a challenge while trying to insert data in the following format: INSERT INTO RELATIONSHIP_CONFIG (USERID, WORKGROUPID, PRIORITY) VALUES (@userId, @WorkgroupId10, @SmartFeedPriority10), (@userId, @WorkgroupId11, @SmartFeedPri ...

Is there a way to identify the presence of a window popup using Selenium with C#?

I am in the process of developing a software program that includes a 'Submit' button to show a list of service providers within a specified area. However, in cases where a provider has offices in multiple locations (such as different states or va ...

Generating an MD5 hash for a UTF16LE string in Javascript (with no BOM and excluding 0-byte at the end) - Illustrated with a C#

I've been trying to figure out how to get an MD5 Hash of a UTF16-LE encoded string in JavaScript for the past few days. I have a method in C# as an example, but I'm not sure how to replicate it in JavaScript. Example: public string GetMD5Hash ( ...

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

"Encountering Devextreme Reactive Errors while navigating on the main client

Attempting to integrate Devextreme with Material Ui in my Typescript React app has been a challenge. Despite following the steps outlined in this documentation and installing all necessary packages, I am encountering issues. I have also installed Material ...

Error in office interop PowerPoint: Registry fault due to E_NOINTERFACE

An error occurred when trying to convert a PowerPoint presentation to PDF. The error message states: 'Unable to cast COM object of type 'System.__ComObject' to event interface type 'Microsoft.Office.Interop.PowerPoint.PresEvents_Event&a ...

What are the differences between the "case when index" statement and the "case index" statement?

I've been doing some research on the "case when index" command, but I'm having trouble finding a clear explanation. Can you tell me more about what "case when index" is? How does it differ from "case when"? When should it be used? Is it specific ...

Guidelines for universal (e.g. <T>) internet user module

Suppose I have created a web control like this: public class TestControl<T> : WebControl { ... } Is there a way to add that control to an .aspx page without using code? I am interested in something like this: <controls:TestControl<int> ...

Minimize repeated database queries to reduce latency and the number of concurrent requests

I have an SQL database connected to my website, housing a table containing a task list (columns separated by "/") like the following: task1 / doTask1.sh / todo task2 / doTask2.sh / done task3 / doTask3.sh / todo task4 / doTask4.sh / todo and so on... ...

Transmit and receive Json data but unable to interpret the response

I am working on an application that requires me to send JSON code through web requests. I am able to establish the connection and send and receive data using GET, POST, PUT, and DELETE methods. However, although I believe I am receiving JSON code in respon ...

What is the method for adjusting CalendarView to automatically display today's date?

Currently utilizing WinUI3/Windows App SDK 1.3 with XAML/C# integration. Issue at hand is the absence of a standard "Today" button on calendar controls in most modern user interfaces. In the WASDK/WinUI environment, the calendar control is referred to as " ...

What is the best way to display individual records from a Web API on the user interface?

Just a heads up: I'm unable to utilize pagination (skip, take) due to the data being sourced from multiple tables. For more information, you can refer to the Report model. I attempted to retrieve the data individually on the UI through WebAPI. The ...

Design blueprint for mysterious JSON structure

I'm seeking a little guidance on how to create a class model for a specific JSON tree that is generated by a webservice. Unfortunately, I have no control over the structure of the JSON. The JSON data looks like this: { "version":"1", "value ...

Tips for efficiently conducting ETL processes in BigQuery without encountering duplicate data

My product table consists of the following columns: id createdOn UpdatedOn along with 76 additional columns. The fields createdOn and UpdatedOn are both defined as TIMESTAMP. The createdOn field serves as the partition key. During every ETL process, rec ...

What is the best way to account for the 'elvis operator' within a given expression?

When connecting to my data from Firebase, I noticed that using the elvis operator is essential to avoid encountering undefined errors. Recently, as I delved into creating reactive forms, I encountered an issue with a component I developed that fetches actu ...

What is the best way to sort a string array in ascending and descending alphabetical order using either C# .NET or Java?

So here's the situation: I've got a string array that looks something like this: String names[] = new String[5]; names[0]="abc"; names[1]="aab"; names[2]="aaacb sf"; names[3]=" ab"; names[4]="hello"; I'm trying to figure out how to sor ...

Encountered an internal server error when attempting to retrieve a response from a web API using HttpClient's PostAsync method in .NET Core 3

_clientRequest = new CustomHttpClient(parameters.AppInstanceID, Cockpit4DIAConnection); HttpContent requestParameter = new ObjectContent<ViewParameters>(parameters, new JsonMediaTypeFormatter()); HttpResponseMessage response = await _cli ...

There are no interactive or clickable elements on this page

Hey there, I'm facing some serious issues while trying to log into Google Adwords using ghostdriver for selenium. Here's a snippet of the code I am using: Dim driver As New PhantomJSDriver Dim options = New PhantomJSOptions() options.Add ...