My questions is similar to this question but I’ve applied the answers and it’s still not working and I’ve used a slightly different approach while storing the data in the DB.
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" }); } }
When I click on save button it reloads the page without changes. I added breakpoints and according to that the employeeFromDb
is clearly going in the .Update
clause but it just refreshes the page and the Database remains unchanged. Here is the screenshot at that breakpoint:
Advertisement
Answer
Glad it worked, so that was just a test. What you were finding about EntityState is really what you should read on from this tutorial – https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-3.1
Entity States The database context keeps track of whether entities in memory are in sync with their corresponding rows in the database, and this information determines what happens when you call the SaveChanges method. For example, when you pass a new entity to the Add method, that entity’s state is set to Added. Then when you call the SaveChanges method, the database context issues a SQL INSERT command.
If you look at the Edit example where Bind properties are passed along with the parameter Id of the record, you could probably use that as a better example for your work. However, if you would like to create a mapper class to convert your request object into an Entity Framework object so it gets updated correctly that could work too. I wonder if you were actually getting an exception before but missed it since the breakpoint wasn’t on that block.
This could be useful too if binding through Ajax json calls – https://stackoverflow.com/a/60180783/8161471