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