提问人:shadow777 提问时间:6/16/2019 最后编辑:shadow777 更新时间:6/22/2019 访问量:720
CRUD 添加新行而不是更新
CRUD adding new row instead of updating
问:
我在 .Net 应用中更新数据时遇到了问题。当我尝试更新时,它会使用新 ID 创建新行,而不是更新现有行。
我没有看到问题出在哪里。也许有人可以帮助解决问题。
这是控制器的方法:
public JsonResult SaveDataInDatabase (StudentViewModel model)
{
var result = false;
try
{
if (model.StudentId > 0)
{
tblStudent Stu = db.tblStudent.SingleOrDefault(x => x.IsDeleted == false && x.StudentId == model.StudentId);
Stu.StudentName = model.StudentName;
Stu.Email = model.Email;
Stu.DepartmentId = model.DepartmentId;
db.SaveChanges();
result = true;
}
else
{
tblStudent Stu = new tblStudent();
Stu.StudentName = model.StudentName;
Stu.Email = model.Email;
Stu.DepartmentId = model.DepartmentId;
Stu.IsDeleted = false;
db.tblStudent.Add(Stu);
db.SaveChanges();
result = true;
}
}
catch (Exception ex)
{
throw ex;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
和 jQuery 函数:
$("#SaveStudentRecord").click(function () {
var data = $("#SubmitForm").serialize();
$.ajax({
type: "Post",
url: "/Home/SaveDataInDatabase",
data: data,
success: function (result) {
alert("Success!..");
window.location.href = "/Home/index";
$("#MyModal").modal("hide");
}
})
})
下面是模型视图:
public class StudentViewModel
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public string Email { get; set; }
public bool? IsDeleted { get; set; }
public int? DepartmentId { get; set; }
public String DepartmentName { get; set; }
}
GetStudentByID 方法:
public JsonResult GetStudentById (int StudentId)
{
tblStudent model = db.tblStudent.Where(x => x.StudentId == StudentId).SingleOrDefault();
string value = string.Empty;
value = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return Json(value, JsonRequestBehavior.AllowGet);
}
答:
0赞
Bosco
6/16/2019
#1
正如您在评论中提到的,将代码更改为此将起作用
tblStudent Stu = db.tblStudent.FirstOrDefault(x => x.IsDeleted == false && x.Email == model.Email);
if (Stu != null)
{
Stu.StudentName = model.StudentName;
Stu.Email = model.Email;
Stu.DepartmentId = model.DepartmentId;
db.Entry(Stu).State = EntityState.Modified;
db.SaveChanges();
result = true;
}
else
{
tblStudent Stu = new tblStudent();
Stu.StudentName = model.StudentName;
Stu.Email = model.Email;
Stu.DepartmentId = model.DepartmentId;
Stu.IsDeleted = false;
db.tblStudent.Add(Stu);
db.SaveChanges();
result = true;
}
只需确保 StudentId 列是自动递增的
上一个:iMacros - 复选框
评论