user6383418
user6383418

Reputation: 415

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

I have been following this tutorial on .NET Core CRUD operations https://learn.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?

Upvotes: 2

Views: 1222

Answers (1)

AlbertK
AlbertK

Reputation: 13227

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"];

Upvotes: 3

Related Questions