.NET Core 2.0 MVC - Programmatically change values before calling TryUpdateModelAsync

asp.net-core asp.net-mvc c# entity-framework-core

Question

I have been following this tutorial on .NET Core CRUD operations https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud Below is my Edit method

[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditUser(string id, ApplicationUser applicationUser)
{
    if (id != null)
    {
        return NotFound();
    }
    var userToUpdate = await _context.ApplicationUser.SingleOrDefaultAsync(u => u.Id == id);
    if(await TryUpdateModelAsync<ApplicationUser>(
        userToUpdate,"",m => m.DateUpdated,m=> m.Name, m=>m.Email))
    {
        try
        {
            if (applicationUser.IsAdmin)
            {
                var x = await _userManager.AddToRoleAsync(applicationUser, "Admin");
                if (!x.Succeeded)
                {

                }
            }
            else
            {
                await _userManager.AddToRoleAsync(applicationUser, "User");
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        catch(DbUpdateException ex)
        {
            //TODO: err
        }
        return View(applicationUser);
    }
}

However, there is no clear documentation on how to then update the fields programmatically before calling the Update using the TryUpdateModelAsync method. For example, I want to set the DateUpdated. Or what if I wanted to make some other field change based on the form value?

1
1
2/14/2018 7:03:18 PM

Accepted Answer

The method TryUpdateModelAsync just updates properties of the userToUpdate and doesn't save to database anything. The properties listed in method params should be in the controller's current IValueProvider(e.g. in FormValueProvider)

I want to set the DateUpdated

If you want to change additional properties that are not exist in the form you can do it anywhere but before the entity will be saved by await _context.SaveChangesAsync();:

userToUpdate.DateUpdated = DateTime.Now;

Or what if I wanted to make some other field change based on the form value?

you can get form values from HttpContext.Request.Form:

userToUpdate.SomeProperty = HttpContext.Request.Form["SomeProperty"];
2
2/15/2018 1:24:29 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow