I have done some research and found that I can use:
string retUrl = "";
if (ViewContext.HttpContext.Request.UrlReferrer != null)
{
retUrl =
ViewContext.HttpContext.Request.UrlReferrer.PathAndQuery;
}
As a way to set a returnUrl and then pass it into a controller via action link.
However, is there any way I can pass a parameter from a form into a controller?
Here’s how my code looks right now:
@using (Html.BeginForm(new { returnUrl = retUrl})) {
@Html.EditorForModel()
<input type="submit" value="Save"/>
}
This works great in the sense that it returns you to the right URL when you submit the form. However, the form doesn’t actually get saved. If I remove that returnUrl parameter it saves the form but it does not redirect properly.
This reason I’m doing this is because this form is accessible from multiple pages and I don’t want to send them all to one page after they submit the form but rather to the previous page.
EDIT
I’ve also tried BeginRouteForm and specifying a controller and action, both approaches did not work.
EDIT
Action source:
[Authorize]
[HttpPost]
public ActionResult EditReview(Review review, string returnUrl)
{
if (ModelState.IsValid)
{
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
reviewRepository.SaveReview(review);
return RedirectToAction("Index");
}
return View(review);
}
To save you form before redirecting you need to switch some lines around in the action method. Instead of:
to