Search code examples
c#asp.netasp.net-mvc-4authenticationreturnurl

ReturnUrl is always null after login


I'm tryin to redirect a user back to the previous page after they login. I tried using the returnUrl parameter but for some reason it's always null.

Here is my code:

Login method:

public ActionResult Login(string returnUrl)
{

    ViewBag.returnUrl = returnUrl;
    return View();
}

The from in the view:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "loginForm", returnUrl = ViewBag.returnUrl }))

Someone got an idea


Solution

  • Your using the wrong overload of BeginForm and rending an attribute for returnUrl rather than a route value. If you need to render an id attribute for the form (seems unnecessary), then

    @using (Html.BeginForm(null, null, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { id = "loginForm" }))
    

    otherwise, just

    @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))