Search code examples
c#asp.netasp.net-mvcasp.net-mvc-4account-management

Enabling Users to Edit Custom Account Settings in MVC


From the bare-bones MVC project template, I've extended ApplicationUser.cs to display a new user account setting called DisplayName (its a display name that people will use in a chat application as part of the site):

public string DisplayName { get; set; }

I have modified the bare-bones MVC project template so that I can register a new account and specify the DisplayName, and I can even see it in my database, so all is good (the process is described here). Anyhow, the problem I am facing now is that I want to allow the user to change this setting, so I have extended the account management page to show an HTML partial page with a text field that displays this setting. When they post this partial page, this action is called:

// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ManagePublicSettings(ManagePublicSettingsViewModel model)
{
    ViewBag.ReturnUrl = Url.Action("Manage");
    if (ModelState.IsValid)
    {
        IdentityResult result = await UserManager.ChangeDisplayName(User.Identity.GetUserId(), model.DisplayName);
        if (result.Succeeded)
        {
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
            return RedirectToAction("Manage", new { Message = ManageMessageId.ChangeAccountSettingsSuccess });
        }
        else
        {
            AddErrors(result);
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}

What should ChangeDisplayName (called by this method) look like? And is this the correct way to extend the account management portal in MVC? Should I extend the ApplicationUserManager class like this? I am fairly new to MVC, and just want to get it right.


Solution

  • No, you should not extend UserManager like that. This is really very simple. You have this code:

    var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
    

    just set the DisplayName property of the user and update them:

    user.DisplayName = Model.DisplayName;
    await UserManager.UpdateAsync(user);