加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 当用户需要再次登录时,Ajax.ActionLink返回div

发布时间:2020-12-16 06:59:03 所属栏目:asp.Net 来源:网络整理
导读:我有一个Ajax.ActionLink导致返回部分视图.但是,如果我的FormsAuthentication过期且用户需要再次登录,则整个登录页面将作为局部视图返回. 这导致完整登录页面出现在我为部分视图预留的div中.所以它看起来像页面上的两个网页. 我在我的控制器和操作上使用[Aut
我有一个Ajax.ActionLink导致返回部分视图.但是,如果我的FormsAuthentication过期且用户需要再次登录,则整个登录页面将作为局部视图返回.

这导致完整登录页面出现在我为部分视图预留的div中.所以它看起来像页面上的两个网页.

我在我的控制器和操作上使用[Authorize]属性.

如何强制将登录页面作为完整视图返回?

解决方法

您可以扩展[Authorize]属性,以便可以覆盖HandleUnauthorizedRequest函数以将JsonResult返回到 AJAX调用.

public class AuthorizeAjaxAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext 
                                                      filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            // It was an AJAX request => no need to redirect
            // to the login url,just return a JSON object
            // pointing to this url so that the redirect is done 
            // on the client

            var referrer = filterContext.HttpContext.Request.UrlReferrer;

            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,Data = new { redirectTo = FormsAuthentication.LoginUrl + 
                            "?ReturnUrl=" + 
                             referrer.LocalPath.Replace("/","%2f") }
            };
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

创建一个Javascript函数来处理重定向:

<script type="text/javascript">
    function replaceStatus(result) {
        // if redirectTo has a value,redirect to the link
        if (result.redirectTo) {
            window.location.href = result.redirectTo;
        }
        else {
            // when the AJAX succeeds refresh the mydiv section
            $('#mydiv').html(result);
        }
    };
</script>

然后在Ajax.ActionLink的OnSuccess选项中调用该函数

Ajax.ActionLink("Update Status","GetStatus",new AjaxOptions { OnSuccess="replaceStatus" })

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读