簡體   English   中英

從復雜的視圖模型更新實體?

[英]Update entity from complex viewmodel?

將我的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);
    }

我需要復雜的viewmodel,因為我有使用不同模型的部分視圖。 如何更新我的用戶?

問題是您的EditViewModelpublic字段組成。 ASP.NET MVC中的默認modelbinder需要公共設置器。 嘗試將您的視圖模型更改為:

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

   public ApplicationUser user { get; set}

   public CSGOAccount CSGOAccount { get; set}
}

它應該工作。 另外,您的財產名稱應為Pascal Cased

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM