TryUpdateModelAsync始终返回false

时间:2019-06-14 21:14:38

标签: c# database asp.net-core model-view-controller

我正在用我的讲师控制器类中端点EditPost上的POST用POST更新数据库中的一位讲师,如果与此有关,我也要更新一个外键。我的TryUpdateModelAsync方法始终返回false,并且仅在它返回true时保存到数据库,导致它永远不会返回true

很多印刷声明

    [HttpPost, ActionName("Edit")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> EditPost(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }
        Console.WriteLine("------------------\n\n\n\n\n\n\n\nlog from edit post\n\n\n\n\n\n\n\n------------------");
        var instructorToUpdate = await _context.Instructors
            .Include(i => i.OfficeAssignment)
            .FirstOrDefaultAsync(s => s.ID == id);

        bool await_result = await TryUpdateModelAsync<Instructor>(
            instructorToUpdate,
            "",
            i => i.FirstMidName, i => i.LastName, i => i.HireDate, i => i.OfficeAssignment);
        Console.WriteLine($"---------------------\n\n\n\n\nawait result: {await_result}\n\n\n\n\n---------------------");
        if (await_result)
        {
            Console.WriteLine("------------------\n\n\n\n\n\n\n\nmade it in try update\n\n\n\n\n\n\n\n------------------");
            if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment?.Location))
            {
                instructorToUpdate.OfficeAssignment = null;
            }
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.)
                ModelState.AddModelError("", "Unable to save changes. " +
                    "Try again, and if the problem persists, " +
                    "see your system administrator.");
            }
            return RedirectToAction(nameof(Index));
        }
        Console.WriteLine("------------------\n\n\n\n\n\n\n\ndidn't make it in try update\n\n\n\n\n\n\n\n------------------");
        return View(instructorToUpdate);
    }

我希望这能更新我的数据库并将我重定向回到教师索引页面

0 个答案:

没有答案