MVC 4添加电子邮件地址进行注册

时间:2016-02-09 20:25:56

标签: asp.net-mvc

我正在使用MVC 4项目的默认注册。我已将Email添加到RegisterModel和UserProfile,我无法弄清楚如何在注册时将电子邮件保存到数据库。任何帮助,将不胜感激。

 [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }

    //
    // POST: /Account/Register
    private DefaultDBContext db = new DefaultDBContext();

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                string confirmationToken = WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                Roles.AddUserToRoles(model.UserName, new[] { "Member" });

                WebSecurity.Login(model.UserName, model.Password);
                //collection.UserID = (int)WebSecurity.CurrentUserId;
                //db.Collections.Add(collection);
                //db.SaveChanges();
                Session["MyMenu"] = null;
                return RedirectToAction("Dashboard", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

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

1 个答案:

答案 0 :(得分:1)

假设您的数据库表是最新的,您可以执行以下操作:

WebSecurity.CreateUserAndAccount(
         model.UserName, 
         model.Password, 
         new { Email = model.Email });

它使用CreateUserAndAccount()方法的以下重载;传递的对象的每一列,propertyValues参数与表中的列相关联。

    //
    // Summary:
    //     Creates a new user profile entry and a new membership account.
    //
    // Parameters:
    //   userName:
    //     The user name.
    //
    //   password:
    //     The password for the user.
    //
    //   propertyValues:
    //     (Optional) A dictionary that contains additional user attributes. The default
    //     is null.
    //
    //   requireConfirmationToken:
    //     (Optional) true to specify that the user account must be confirmed; otherwise,
    //     false. The default is false.
    //
    // Returns:
    //     A token that can be sent to the user to confirm the user account.
    //
    // Exceptions:
    //   System.InvalidOperationException:
    //     The WebMatrix.WebData.SimpleMembershipProvider.Initialize(System.String,System.Collections.Specialized.NameValueCollection)
    //     method was not called.-or-The Overload:WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection
    //     method was not called.-or-The WebMatrix.WebData.SimpleMembershipProvider
    //     membership provider is not registered in the configuration of your site.
    //     For more information, contact your site's system administrator.
    public static string CreateUserAndAccount(string userName, string password, object propertyValues = null, bool requireConfirmationToken = false);