Reputation: 10753
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);
}
Upvotes: 1
Views: 6188
Reputation: 2733
To save you form before redirecting you need to switch some lines around in the action method. Instead of:
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
reviewRepository.SaveReview(review);
return RedirectToAction("Index");
to
reviewRepository.SaveReview(review);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index");
Upvotes: 4
Reputation: 7200
If I am understanding you correctly, you are actually changing the ACTION
method on the form, so I am not surprised it didn't save. I'd get rid of that and just post to the controller/action as you originally intended. Then add the retUrl
as a hidden input to post along with the rest of the form data.
@using (Html.BeginForm()) {
@Html.EditorForModel()
<input type="hidden" name="returnUrl" value="@retUrl" />
<input type="submit" value="Save"/>
}
Edit:
You can also use the Html helper.
@Html.Hidden("returnUrl", retUrl)
Upvotes: 1
Reputation: 1935
Like this?
@using(Html.BeginForm("act","contr",FormMethod.Post) {
@Html.Hidden("returnUrl",ViewContext.HttpContext.Request.Url.PathAndQuery)
<input type="submit" />
}
There shouldn't be any issue with passing the same in the BeginForm method -- either will bind to ActionMethod(string returnUrl)
.
Upvotes: 1