无论调用javascript函数如何执行c#代码

时间:2013-04-16 19:42:00

标签: javascript asp.net-mvc razor simplemembership

即使没有执行功能注销,我也遇到了用户一直注销的问题。看起来这是因为代码在c#中(这是在剃须刀布局页面mvc4)

<script type="text/javascript">
    var idleTimer = 0;
    function notIdle() 
    {
        clearTimeout(idleTimer);     
        idleTimer = setTimeout(function () { logout() }, 5000);
    }

    function logout()           
    {
        @if (Request.IsAuthenticated )
        {
            WebSecurity.Logout();                  
        }
        window.location.reload();
        clearTimeout(idleTimer);

    }         
</script> 

1 个答案:

答案 0 :(得分:0)

如上所述,您的C#代码将在页面加载时运行。我可以建议创建一个控制器方法Logout,将代码放在那里,并在脚本logout()函数中重定向到该方法。代码如下:
HTML

<button onclick="logout()">Logout</button>

<强>的Javascript

    //I don't really know your logic behind those timeouts, so I leave them as is
    var idleTimer = 0;
    function notIdle() 
    {
        clearTimeout(idleTimer);     
        idleTimer = setTimeout(function () { logout() }, 5000);
    }

    function logout()           
    {
        location.href = "Home/Logout"; 
        //"Home" is the name of your controller, where you will put the Logout method.
    } 

<强> C#

public ActionResult Logout()
{
    if (Request.IsAuthenticated)
    {
        WebSecurity.Logout();
    }
    return RedirectToAction("Index", "Home"); //redirect to your previous page
}