weixin_33726313 2017-03-13 01:32 采纳率: 0%
浏览 38

超时后重定向视图

I have a view Index, called from Index Action inside EnqueteController, which has all my javascript code in it. This view RenderPartial a form, _EnqueteForm which has all my form inputs. In my javascript section (in Index) I have the following:

@section Scripts{

<script type="text/javascript">

var IDLE_TIMEOUT = 10; //seconds
var _idleSecondsCounter = 0;
document.onclick = function () {
    _idleSecondsCounter = 0;
};
document.onmousemove = function () {
    _idleSecondsCounter = 0;
};
document.onkeypress = function () {
    _idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);

function CheckIdleTime() {
    _idleSecondsCounter++;
    if (oPanel)
        oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
    if (_idleSecondsCounter >= IDLE_TIMEOUT) {
        $.ajax({
            cache: false,
            url: '/Enquete/Inactive',
            type: 'POST',
            dataType: "json",
            data: $('form').serialize(),
        });
    }
}

}

After 10 seconds of inactivity, it's calling Inactive action from Enquete Controller.

This action looks like this:

    [HttpPost]
    public ActionResult Inactive([System.Web.Http.FromBody] InfoFormulaireEnqueteModele m)
    {
        int userId = this.UserId();

        LibraryEnquete.EnregistrerFormulaire(m, userId);
        TransitionEtatPrecedent(m.HevEvenementID, userId);
        return View("Logout");
    }

My action is called correctly after 10s and it's calling LibraryEnquete.EnrigistrerFormulaire and also TransitionEtatPrecedent. But my problems are:

1) It wont change to the 'Logout' view

2) For some reason, my Inactive method is called from other page?! After one call, I stop the application and once I restart it, from the main page (which is not the EnqueteController Index page), it's calling the Inactive method like 20 times until I stop the application

  • 写回答

1条回答 默认 最新

  • weixin_33717117 2017-03-13 02:09
    关注

    Ajax calls do not handle redirect responses (http status code 3xx).

    By returning the view to an ajax call, you are just getting the view rendered as string in the ajax success event handler.

    In order for the browser to render the logout view, you can just proceed to submit the form without using ajax:

    if (_idleSecondsCounter >= IDLE_TIMEOUT) {
        $('form').submit();
    }
    

    If the form's action it's not poiting to /Enquete/Inactive, you can change the action before submiting the form:

    if (_idleSecondsCounter >= IDLE_TIMEOUT) {
        $('form').prop('action', '/Enquete/Inactive');
        $('form').submit();
    }
    
    评论

报告相同问题?