Reputation: 9621
I have a method:
public ActionResult AddProductToCart(int productId)
{
var product = _productService.GetProductById(productId);
if (product == null)
return RedirectToAction("Index", "Home");
int productVariantId = 0;
if (_shoppingCartService.DirectAddToCartAllowed(productId, out productVariantId))
{
var productVariant = _productService.GetProductVariantById(productVariantId);
var addToCartWarnings = _shoppingCartService.AddToCart(_workContext.CurrentCustomer,
productVariant, ShoppingCartType.ShoppingCart,
string.Empty, decimal.Zero, 1, true);
if (addToCartWarnings.Count == 0)
//return RedirectToRoute("ShoppingCart");
else
return RedirectToRoute("Product", new { productId = product.Id, SeName = product.GetSeName() });
}
else
return RedirectToRoute("Product", new { productId = product.Id, SeName = product.GetSeName() });
}
You see the line which is commented out: I want there to not trigger any redirect but just stay on the same page from where this request was made.
If I put return View()
it's not fine because it will search for View with this name while this method is a simple action to add to cart..
Can you please give me a solution of how to Redirect to current url or to stay on the same page?
Upvotes: 10
Views: 20901
Reputation: 101594
Assuming you mean return to where you were before visiting that controller:
return Redirect(Request.UrlReferrer.ToString());
Keep in mind that if you POSTed to get to that [previous] page, you're going to be at a loss since you're not mimicking the same request.
Upvotes: 6
Reputation: 1038710
You could pass an additional returnUrl
query string parameter to this method indicating the url to get back to once the product has been added to the cart:
public ActionResult AddProductToCart(int productId, string returnUrl)
so that you can redirect back to wherever you were:
if (addToCartWarnings.Count == 0)
{
// TODO: the usual checks that returnUrl belongs to your domain
// to avoid hackers spoofing your users with fake domains
if (!Url.IsLocalUrl(returnUrl))
{
// oops, someone tried to pwn your site => take respective actions
}
return Redirect(returnUrl);
}
and when generating the link to this action:
@Html.ActionLink(
"Add product 254 to the cart",
"AddProductToCart",
new { productId = 254, returnUrl = Request.RawUrl }
)
or if you are POSTing to this action (which by the way you should probably be because it is modifying state on the server - it adds a product to a cart or something):
@using (Html.BeginForm("AddProductToCart", "Products"))
{
@Html.Hidden("returnurl", Request.RawUrl)
@Html.HiddenFor(x => x.ProductId)
<button type="submit">Add product to cart</button>
}
Another possibility is to use AJAX to invoke this method. This way the user will stay on the page wherever he was before calling it.
Upvotes: 16