如何在asp.net mvc3中访问帐户控制器中的UserId?

时间:2012-06-17 04:52:36

标签: asp.net-mvc asp.net-mvc-3

我想在注册后为任何用户分配一行表。此表有一个名为UserId的列和其他一些列。我想将此表的UserId设置为新注册用户的UserId,并将其他值设置为0.我想在Register函数中执行此操作。但我不知道如何在Account控制器的Register功能中访问UserID。 我使用默认帐户控制器及其功能。注册代码功能是:

[HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

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

2 个答案:

答案 0 :(得分:2)

假设User是你的Model,控制器应该是这样的

class Account:Controller{

[HttpPost]
ActionResult Register(User myModel){

var myUserId = myModel.UserId;

}
}

你的观点应该从这样的事情开始

@model User

答案 1 :(得分:1)

如果您在创建UserId时引用为用户生成的唯一标识符,您可以将其命名为,

[HttpPost]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        MembershipCreateStatus createStatus;
        var user = Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

        if (createStatus == MembershipCreateStatus.Success)
        {
            var userId = (Guid) user.ProviderUserKey; //The unique identifier just created

            FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("", ErrorCodeToString(createStatus));
        }
    }

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