Question

I'm trying to build a two-step custom registration for users in my ASP.NET MVC 4 application. This involves redirecting users after registration to the Edit view in the User Controller. I've tweaked the code in the stock Account Controller template to achieve this.

 public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Edit", "User",  new { id = WebSecurity.CurrentUserId });
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }


            return View(model);
        }

However when I run this I get a 404 on the address bar it shows

http://localhost:17005/User/Edit/-1

Which means it's going into the Edit action of user controller, but then ending up with a Id of -1. Any help would be appreciated.

Was it helpful?

Solution

Membership.GetUser().ProviderUserKey

Alternatively you could not pass a user id to the edit action and have the code use the currently logged in user.

RedirectToAction("Edit", "User");

In your user controller

[Authorize]
public ActionResult Edit()
{
    object userId = Membership.GetUser().ProviderUserKey;
}

Please excuse brevity as I am currently on my mobile

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top