ajax调用上的重复标头

时间:2012-12-28 23:08:40

标签: asp.net asp.net-mvc asp.net-mvc-3

您已经创建了一个链接来执行对控制器的ajax调用,以便更新ID为UpdateCart的范围。问题是,如果用户未进行身份验证,则会将其发送到“登录”页面,并且会在页:

enter image description here

enter image description here

从图像中可以看出我的整个标头标签是如何重复并添加到span标签内的。这是我的代码:

    @Ajax.ActionLink("Add To Cart" ,
                                 "AddToCart" ,
                                 "Products", 
                                 new {
                                        ProductId = @products.ElementAt(0).Value
                                     },
                                 new AjaxOptions{

                                                   InsertionMode = InsertionMode.Replace,
                                                   UpdateTargetId = "UpdateCart",
                                                   HttpMethod = "GET"
                                                })
public ActionResult AddToCart(string ProductId)
        {
            if( User.Identity.IsAuthenticated ) {
                string username = User.Identity.Name;

                CartHelperClass.AddToCart(ProductId , username);
                ViewBag.ItemsInCart = CartHelperClass.CountItemsInCart(username);

                return PartialView("_AddToCart");
            } else {
                return RedirectToAction("LogIn" , "Account" , new {
                    returnUrl = "Products"
                });
            }     
        }

如何停止创建重复标题?

1 个答案:

答案 0 :(得分:2)

看看following blog post。在这篇文章中,Phil Haack解释了如何配置Forms Authentication模块以停止为未经过身份验证的用户重定向到LogOn页面以获取AJAX请求。你可以让它为客户端返回一个真正的401状态代码,用于AJAX请求。

然后可以在客户端上轻松拦截此401并执行您想要的任何操作 - 例如使用window.location.href方法手动将浏览器重定向到LogOn页面。

因此,在您的情况下,您只需订阅ajaxComplete()处理程序,在此处理程序中,您可以测试响应状态是否为401,这意味着用户未经过身份验证,您将重定向到LogOn页面

因此,一旦安装了AspNetHaack NuGet(Install-Package AspNetHaack),您所要做的就是全局订阅页面中的.ajaxComplete()处理程序:

<script type="text/javascript">
    $(document).ajaxComplete(function (e, xhr, settings) {
        if (xhr.status == 401) {
            alert('Sorry you must be authenticated in order to use this action. You will now be redirected to the LogOn page');
            window.location.href = '@FormsAuthentication.LoginUrl';
        }
    });
</script>

当然你设置了一个,你应该停止从你的AJAX控制器动作重定向,因为这是没有意义的。您的控制器操作现在将如下所示:

[Authorize]
public ActionResult AddToCart(string productId)
{
    string username = User.Identity.Name;
    CartHelperClass.AddToCart(productId , username);
    ViewBag.ItemsInCart = CartHelperClass.CountItemsInCart(username);
    return PartialView("_AddToCart");
}

TODO:我真的建议您重构此AddToCart操作,以便它停止使用ViewBag,但它会将强类型视图模型传递给您的局部视图。