0

我正在同一页面上处理登录和注册。当我单击注册按钮时,我在不同的控制器中处理,但我不想使用我的 URL。

示例:当我请求时

http:localhost:1853/Account/RegisterLogin

如果模型无效,我想在发布时我的 URL 仍然没有改变。

    // GET: /Account/RegisterLogin

    [AllowAnonymous]
    public ActionResult RegisterLogin(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        ViewData["RegisterModel"] = new RegisterModel();
        ViewData["LoginModel"] = new LoginModel();
        return View();
    }

    //
    // POST: /Account/Register

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Gender = model.Gender, FirstName = model.FirstName, LastName = model.LastName, BirthDate = model.BirthDate, Email = model.Email }, false);
                WebSecurity.Login(model.UserName, model.Password);
                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        // If we got this far, something failed, redisplay form
        ViewData["RegisterModel"] = model;
        ViewData["LoginModel"] = new LoginModel();
        return View("RegisterLogin");
    }

谢谢你的帮助!

4

1 回答 1

0

我建议您将模型发布到具有相同名称的同一控制器中的操作,并在模型中添加一个标志,显示用户是否登录或注册,并根据标志的值执行适当的操作。它允许您保存当前模型状态值并保留在 URL 上

    //GET /Account/Register
    [AllowAnonymous]
    public ActionResult RegisterLogin(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View(new RegisterLoginModel() { ReturnUrl = returnUrl, IsLogin = false });
    }
    //POST /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult RegisterLogin(RegisterLoginModel model)
    {
        if (!ModelState.IsValid)
        {
            if (!model.IsLogin)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Gender = model.Gender, FirstName = model.FirstName, LastName = model.LastName, BirthDate = model.BirthDate, Email = model.Email }, false);
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }
            else
            {
                //do something
            }
        }

        return View(model);
    }
于 2013-09-03T10:23:22.060 回答