Return URL's in ASP.NET MVC Postbacks

One of the neat things about the ASP.NET MVC framework is the ability to reuse bits of user interface code. A problem can present itself when you create a reusable view that posts data. Hard coding a redirect can lead to a difficult and frustrating user experience. I'm going to show you a simple way to redirect back to the originating page.

The theory is simple, pass the return URL into your form and store it as a hidden field in the form. When the form posts, you can use this field to redirect appropriately.

As the most basic example, you can call a Create action in your controller from any page on your site and it will redirect back to the originating page. The controller code to render your form may look like something like:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
   // pass the referrer to the view
   ViewData["referringUrl"] = Request.UrlReferrer;

   // do some other stuff

   return View();
}

Next you will want to create a hidden field in your view so that the referring url will be posted.

  <% Html.BeginForm("Insert"); %>
  <%= Html.Hidden("referringurl") %>
  // have your form here
  <% Html.EndForm() %>

Now in your controller, you use the referral url to redirect appropriately:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Insert(string referringUrl)
{
    // perform your operations
   
    if(string.IsNullOrEmpty(referringUrl))
       // redirect to a default page
    else
       return Redirect(referringUrl);
}

As a final caution, IE has issue with tracking the referring url when JavaScript is used for redirection. Refer to the blog post Where, oh where is my referer (sic) for more information.

If you want to manually provide the ReturnUrl to your form, you can simply pass it into the Get Create Action Method and use the Request.UrlReferrer as a backup:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create(string urlreferrer)
{  
   // pass the referrer to the view
   if(!string.IsNullOrEmpty(urlreferrer))
      ViewData["referringUrl"] = urlreferrer;
   else
      ViewData["referringUrl"] = Request.UrlReferrer;

   // do some other stuff

   return View();
}

Finally, if you are working with a partial, simply pass the ViewData["referringUrl"] to the partial view and it should perform the same as above.

Comments

#1 Anonymous

Thank you!

Recent comments