检索到数据,但未保存或更新asp.net core 3.1

6qqygrtg  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(274)

我的问题类似于这个问题,但我已经应用了答案,它仍然不起作用,我在数据库中存储数据时使用了一种稍微不同的方法。
员工模型类

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

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

键入与保存相关的脚本代码

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);
        }
    }

保存按钮视图代码

<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>

与保存相关的控制器代码

[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" });
            }
        }

当我点击保存按钮时,它会重新加载页面而不做任何更改。我添加了断点,然后 employeeFromDb 显然是在 .Update 但它只是刷新页面,数据库保持不变。以下是该断点处的屏幕截图:

myss37ts

myss37ts1#

很高兴它成功了,所以那只是个测试。关于entitystate,您所发现的内容实际上是您应该从本教程中阅读的内容-https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-3.1
实体状态数据库上下文跟踪内存中的实体是否与数据库中相应的行同步,此信息确定调用savechanges方法时发生的情况。例如,将新实体传递给add方法时,该实体的状态设置为added。然后,当您调用savechanges方法时,数据库上下文会发出一个sqlinsert命令。
如果您看一下edit示例,其中bind属性与记录的参数id一起传递,您可能会将其用作更好的示例。但是,如果您想创建一个Map器类来将您的请求对象转换为实体框架对象,以便正确地更新它,那么也可以工作。我想知道你是否真的得到一个异常之前,但错过了它,因为断点不在该块上。
如果通过ajax json调用进行绑定-https://stackoverflow.com/a/60180783/8161471

相关问题