.NET Core 更新部分字段方法总结

一、利用TryUpdateModelAsync

        此方法首先查询出实体数据,然后根据lambda表达式中的字段进行更新对应的实体字段,注意lambda表达式,都为这样的参数格式o=>o.x1,o=>o.x2而不是o=>o.x1,o.x2

        [ValidateAntiForgeryToken]

        public async Task<ActionResult> EditAsync(int? id)
        { 
            if (id ==null)
            {
                return NotFound();
            }
            if (ModelState.IsValid)
            {
                try
                {
                    var q = dbContext.LeaveRecord.Find(id);
                    if (await TryUpdateModelAsync(q, "", o => o.PersonName, o => o.LeaveType,  o => o.Sex))
                    {
                        await dbContext.SaveChangesAsync();
                    }
                }
                catch
                {
                    return View();
                }
                return RedirectToAction(nameof(Index));
            }
            return View();
        }

二、查询出实体,然后将表单form中的实体字段值赋给查询出来的实体对应字段

        [ValidateAntiForgeryToken]
        public ActionResult EditAsync(int? id, LeaveRecord leaveRecord)
        { 
            if (id ==null)
            {
                return NotFound();
            }
            if (ModelState.IsValid)
            {
                try
                {
                    var q = dbContext.LeaveRecord.Find(id);
                    q.PersonName = leaveRecord.PersonName;
                    q.Sex = leaveRecord.Sex;
                    q.LeaveType = leaveRecord.LeaveType;
                    q.LeaveReason = leaveRecord.LeaveReason;
 
                    dbContext.Update(q);
                    dbContext.SaveChanges();
                }
                catch
                {
                    return View();
                }
                return RedirectToAction(nameof(Index));
            }
            return View();
        }

三、字段绑定更新部分,将所有字段值读出来,然后在html中将不更新的字段设置为readonly,这样用户只能操作需要更新的字段值,但这也有一个问题,如果用户懂计算机,将实体在html中的readonly去掉,会导致后台更新数据 的同时会把值更新

<input type="text" readonly asp-for="Title" />

posted @ 2022-05-01 19:05  燕过留痕  阅读(1148)  评论(0)    收藏  举报