Alex
Alex

Reputation: 121

Extending "Manage.cshtml" out of the box VS 2013

I am trying to adapt the registration and manage views that come out of the box with the new AspNetIdentity (VS 2013 / MVC5 / EF6). I have been pretty successful with extending the properties of registration, combining new elements with the set user name and password registration, but now I am failing miserable at populating the new fields, or ANY fields in the manage account view. I tried adding the @Html.HiddenFor(model => model.Id) to the view but that isn't working even though I added var id = User.Identity.GetUserId(); to the AccountController. I have been staring at the AccountController comparing the code to the CRUD "Edit" control from another scaffold. Do I need a new public ActionResult or public async Task altogether or can I adapt the ones that are already there?

I am resisting posting code as it is literally OUT OF THE BOX, but any help would be greatly appreciated.

UPDATE.

Now this beats all.. I was working from home this weekend, transferred my files to my work machine by Remote Access the tested remotely and voila! There was my user name and old password (hashed of course) correctly displaying in my Manage.cshtml. However now that I am sitting at my work computer - those fields are once again blank..

I resisted but here is my code; AccountViewModel.cs

public class ManageUserViewModel
{
    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Current password")]
    public string OldPassword { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
    [DataType(DataType.Password)]
    [Display(Name = "New password")]
    public string NewPassword { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm new password")]
    [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
}

AccountController.cs

// GET: /Account/Manage
public ActionResult Manage(ManageMessageId? message)
{
    ViewBag.StatusMessage =
        message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
        : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
        : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
        : message == ManageMessageId.Error ? "An error has occurred."
        : "";
    ViewBag.HasLocalPassword = HasPassword();
    **var user = new ApplicationUser()
    {
        UserName = ViewBag.UserName,
        FirstName = ViewBag.FirstName,
        LastName = ViewBag.LastName,
        Email = ViewBag.Email
    };**

    ViewBag.ReturnUrl = Url.Action("Manage");
    return View();
}

//
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Manage(ManageUserViewModel model)
{
    bool hasPassword = HasPassword();
    ViewBag.HasLocalPassword = hasPassword;
    ViewBag.ReturnUrl = Url.Action("Manage");
    if (hasPassword)
    {
        if (ModelState.IsValid)
        {
            IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
            ViewBag.UserName = model.UserName;
            ViewBag.FirstName = model.FirstName;
            ViewBag.LastName = model.LastName;
            ViewBag.Email = model.Email;
            if (result.Succeeded)
            {
                return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
            }
            else
            {
                AddErrors(result);
            }
        }
        else
        {
            // User does not have a password so remove any validation errors caused by a missing OldPassword field
            ModelState state = ModelState["OldPassword"];
            if (state != null)
            {
                state.Errors.Clear();
            }
            if (ModelState.IsValid)
            {
                IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
                ViewBag.UserName = model.UserName;
                ViewBag.FirstName = model.FirstName;
                ViewBag.LastName = model.LastName;
                ViewBag.Email = model.Email;
                if (result.Succeeded)
                {
                    return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                }
                else
                {
                    AddErrors(result);
                }
            }
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}

For one thing, that new user is clearing all my fields - but I am too much of a newbee to quite get the syntax I need to hold the data...

Upvotes: 1

Views: 656

Answers (1)

Alex
Alex

Reputation: 121

YESSSSSS!!!!

Finally figured out what I was doing wrong;

AccountController.cs - that var user = new ApplicationUser() was my downfall. Have now replaced it with;

        ViewBag.HasLocalPassword = HasPassword();
        var user = UserManager.FindById(User.Identity.GetUserId());
        var model = new ManageUserViewModel
        {
            UserName = user.UserName,
            FirstName = user.FirstName,
            LastName = user.LastName,
            Email = user.Email,
            OldPassword = user.PasswordHash
        };
        return View(model);
    }

And now my fields are populated - but can anyone tell me why the OldPassword field is not populating?

Next I will test if it is actually updating all fields!

Upvotes: 0

Related Questions