返回asp.net mvc中的当前URL

Cri*_*riu 10 razor asp.net-mvc-3

我有一个方法:

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() });
    }
Run Code Online (Sandbox Code Playgroud)

你看到被注释掉的行:我希望那里不会触发任何重定向,而只是停留在发出此请求的同一页面上.

如果我return View()说它不好,因为它将搜索具有此名称的View,而此方法是添加到购物车的简单操作..

你能给我一个如何重定向到当前网址或保持在同一页面的解决方案吗?

Dar*_*rov 16

您可以将另一个returnUrl查询字符串参数传递给此方法,指示将产品添加到购物车后返回的网址:

public ActionResult AddProductToCart(int productId, string returnUrl)
Run Code Online (Sandbox Code Playgroud)

这样你就可以重定向回到你所在的地方:

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);
}
Run Code Online (Sandbox Code Playgroud)

并在生成此操作的链接时:

@Html.ActionLink(
    "Add product 254 to the cart", 
    "AddProductToCart", 
    new { productId = 254, returnUrl = Request.RawUrl }
)
Run Code Online (Sandbox Code Playgroud)

或者如果你正在POST这个动作(顺便说一句,你应该是因为它正在修改服务器上的状态 - 它会将产品添加到购物车或其他东西):

@using (Html.BeginForm("AddProductToCart", "Products"))
{
    @Html.Hidden("returnurl", Request.RawUrl)
    @Html.HiddenFor(x => x.ProductId)
    <button type="submit">Add product to cart</button>
}
Run Code Online (Sandbox Code Playgroud)

另一种可能性是使用AJAX来调用此方法.这样,用户在调用它之前将无论身在何处都会留在页面上.


Bra*_*tie 6

假设您的意思是在访问该控制器之前返回到您所在的位置:

return Redirect(Request.UrlReferrer.ToString());
Run Code Online (Sandbox Code Playgroud)

请记住,如果你发布到那个[上一页]的页面,你将会因为你没有模仿相同的请求而感到茫然.