[英]Data is retrieved but is not getting saved or updated ASP.NET Core 3.1
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员工 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 Controller 保存相关代码
[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.我添加了断点,据此,
employeeFromDb
显然在.Update
子句中,但它只是刷新页面并且数据库保持不变。 Here is the screenshot at that breakpoint:这是该断点处的屏幕截图:
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
您对 EntityState 的发现确实是您应该从本教程中阅读的内容 - 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.
实体状态 数据库上下文跟踪 memory 中的实体是否与其在数据库中的相应行同步,并且此信息确定调用 SaveChanges 方法时会发生什么。 For example, when you pass a new entity to the Add method, that entity's state is set to Added.
例如,当您将新实体传递给 Add 方法时,该实体的 state 设置为已添加。 Then when you call the SaveChanges method, the database context issues a SQL INSERT command.
然后,当您调用 SaveChanges 方法时,数据库上下文会发出 SQL INSERT 命令。
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.如果您查看 Edit 示例,其中 Bind 属性与记录的参数 Id 一起传递,您可能会将其用作您工作的更好示例。 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.
但是,如果您想创建一个映射器 class 以将您的请求 object 转换为实体框架 object 以便正确更新它也可以工作。 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如果通过 Ajax json 调用绑定 - https://stackoverflow.com/a/60180783/8161471 ,这也可能很有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.