【问题标题】:Update entity from complex viewmodel?从复杂的视图模型更新实体?
【发布时间】:2017-10-08 17:56:01
【问题描述】:

将我的 ApplicationUser 放入视图模型后,我无法更新它。如果我直接通过 ApplicationUser 它更新就好了。

我的视图模型如下所示:

public class EditViewModel
{
    public List<ApplicationUser> users;

    public ApplicationUser user;

    public CSGOAccount CSGOAccount;
}

然后在我的表单中,我在我的所有属性上调用 user.Property,就像这样:

<div class="form-group">
            <label asp-for="user.FirstName" class="control-label"></label>
            <input asp-for="user.FirstName" class="form-control" />
            <span asp-validation-for="user.FirstName" class="text-danger"></span>
</div>

这是我认为出现问题的地方,但我不确定原因。我有一个理论,没有值永远不会传递给模型,因此没有什么要更新的,因为我的 TryUpdateModel 返回 true 并且没有捕获到异常:

    [HttpPost, ActionName("EditCoach")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> EditCoachInfo(string id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var userToUpdate = await _context.Users
            .Include(i => i.Coach)
            .SingleOrDefaultAsync(i => i.Id == id);
        if (await TryUpdateModelAsync<ApplicationUser>(
            userToUpdate,
            "",
            i => i.FirstName, i => i.LastName, i => i.Email, i => i.UserName, i => i.EmailConfirmed, i => i.PhoneNumber, i => i.PhoneNumberConfirmed, i => i.LockoutEnd, i => i.LockoutEnabled, i => i.AccessFailedCount, i => i.Coach))
            if (userToUpdate.Coach != null)
            {
                try
                {
                    await _context.SaveChangesAsync();
                    TempData["EditStatus"] = "Profilen blev opdateret";
                }
                catch (DbUpdateException /* ex */)
                {
                    //Log the error (uncomment ex variable name and write a log.)
                    TempData["EditStatus"] = "Fejl - Ikke i stand til at gemme ændringer. " +
                        "Prøv igen, eller kontakt din system adminstrator hvis problemet" +
                        "er vedvarende";
                }
            }

        EditViewModel model = new EditViewModel()
        {
            user = userToUpdate,
        };

        return View(model);
    }

我需要复杂的视图模型,因为我有使用不同模型的部分视图。如何更新我的用户?

【问题讨论】:

    标签: c# entity-framework asp.net-identity viewmodel asp.net-core-2.0


    【解决方案1】:

    问题是您的 EditViewModel 包含 public 字段。 ASP.NET MVC 中的默认模型绑定器需要公共设置器。尝试将您的视图模型更改为:

    public class EditViewModel
    {
       public List<ApplicationUser> users { get; set}
    
       public ApplicationUser user { get; set}
    
       public CSGOAccount CSGOAccount { get; set}
    }
    

    它应该可以工作。此外,您的属性名称应该是 Pascal Cased

    【讨论】:

    • 不幸的是它没有解决问题。还有其他想法吗?
    猜你喜欢
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多