简体   繁体   中英

Update entity from complex viewmodel?

After putting my ApplicationUser into a viewmodel I'm not able to update it. If I pass the ApplicationUser directly it updates just fine.

My viewmodel looks like this:

public class EditViewModel
{
    public List<ApplicationUser> users;

    public ApplicationUser user;

    public CSGOAccount CSGOAccount;
}

In my form I then call user.Property on all my properties just like this:

<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>

This is where I think something is going wrong but I am uncertain why. I have a theory that no value is never passed to the model, thus there is nothing to update because my TryUpdateModel returns true and no exception is caught:

    [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);
    }

I need the complex viewmodel because I have partial views that use a different model. How can I update my user?

The problem is your EditViewModel consists of public fields. The default modelbinder in ASP.NET MVC needs public setters. Try changing your viewmodel to:

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

   public ApplicationUser user { get; set}

   public CSGOAccount CSGOAccount { get; set}
}

and it should work. Also your property names should be Pascal Cased

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM