views:

97

answers:

2

I am trying to register a new user and also understand how to get the new userID so i can start creating my own user tables with a userID mapping to the asp.net membership user table.

Below is my code:

 [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Register(string userName, string email, string position, string password, string confirmPassword)
    {

        ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        ViewData["position"] = new SelectList(GetDeveloperPositionList());

        if (ValidateRegistration(userName, email, position, password, confirmPassword))
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus = MembershipService.CreateUser(userName, password, email);

            if (createStatus == MembershipCreateStatus.Success)
            {
                FormsAuth.SignIn(userName, false /* createPersistentCookie */);

                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
            }
        }

        // If we got this far, something failed, redisplay form
        return View();
    }

I've done some research and many sites inform me to use Membership.GetUser().ProviderUserKey; but this throws an error as Membership is NULL.

I placed this line of code just above "return RedirectToAction("Index", "Home");" within the if statement.

Please can someone advise me on this...

Thanks in advance

A: 

This will retrieve the ProviderKey:

if (createStatus == MembershipCreateStatus.Success)
{
     FormsAuth.SignIn(userName, false /* createPersistentCookie */);

     MembershipUser newUser = Membership.GetUser(model.UserName);
     string key = newUser.ProviderUserKey.ToString();

     return RedirectToAction("Index", "Home");
}
JcMalta
A: 

Create the user using the MembershipProvider, this will return a MembershipUser instance. Where you can access the ProviderKey to access the Id.

MembershipCreateStatus status;
MembershipUser user = Membership.Provider.CreateUser(userName, password, email, null, null, true, null, out status);
if (status == MembershipCreateStatus.Success)
{
   object key = user.ProviderUserKey;
}
Andre van Heerwaarde