在MVC4中重写Url

时间:2013-06-02 16:07:31

标签: asp.net-mvc-4 url-rewriting

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

示例:当我请求时

  

的http:本地主机:1853 /帐户/ RegisterLogin

我希望当我发布模型无效时,我的网址仍未更改。

    // 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");
    }

感谢您的帮助!

1 个答案:

答案 0 :(得分: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);
    }