Refresh Page on Back Click - MVC 4

前端 未结 3 658
南旧
南旧 2021-02-04 14:19

What would be a simple way to force my ActionResult to always fire when I hit this page? On browser back click, for instance, this will not execute.



        
相关标签:
3条回答
  • 2021-02-04 14:38

    You could try the onunload event and ajax:

    <script>
       window.onunload = function () {
          $.ajax({
             url: '/ControllerName/Index',
             type: 'POST',
             datatype: "json",
             contentType: "application/json; charset=utf-8"
          });
       };
    </script>
    
    0 讨论(0)
  • 2021-02-04 14:48

    Disabling cache on the ActionResult forces the page to refresh each time rather than rendering the cached version.

    [OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
    public ActionResult Index()
    {
        //do something always
    
        return View();
    }
    

    Now when you click the browsers back button, this is hit every time.

    0 讨论(0)
  • 2021-02-04 15:01

    Adding this code to my HTML works just fine for me:

    <input id="alwaysFetch" type="hidden" />
    <script>
        setTimeout(function () {
            var el = document.getElementById('alwaysFetch');
            el.value = el.value ? location.reload() : true;
        }, 0);
    </script>
    

    This might come handy for those who prefer not to deal with server side code as opposed to the accepted solution.

    All it does is assign a value to a hidden input on first load which will remain on the second load in which case the page is force refreshed.

    0 讨论(0)
提交回复
热议问题