10

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.

public ActionResult Index()
{
    //do something always

    return View();
}
aw04
  • 10,857
  • 10
  • 56
  • 89

3 Answers3

22

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.

aw04
  • 10,857
  • 10
  • 56
  • 89
  • 1
    what about using `VaryByParam = "None"` as mentioned [here](http://stackoverflow.com/questions/21906971/how-to-refresh-asp-net-mvc-page-when-hitting-browser-back-button) is it ok ? – Shaiju T Oct 28 '15 at 08:15
1

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>
Dumisani
  • 2,988
  • 1
  • 29
  • 40
  • I thought about something like this, wasn't sure if it was a good idea to try and redirect onunload though. Anything I should be concerned about or is this an acceptable thing to do that works cross-browser? Also, how would I know the user was trying to navigate back? I don't want to always redirect to this page. – aw04 Mar 18 '14 at 14:10
  • The only thing you should be concerned about is that your action will be called on browser back button click and refresh button click. Even when you do some postback on your page. I once came across this issue and this is the only way I could solve it. http://stackoverflow.com/q/21400594/2174170 – Dumisani Mar 18 '14 at 14:15
  • Thanks, the link to your question was helpful. I'm thinking I don't need to take such a radical approach in my case though. I can get by with something on the ready event of my Index rather than when leaving the next page (just don't know what it is yet). I'd rather not touch the default back-click behavior if I don't have to :) – aw04 Mar 18 '14 at 14:24
0

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.

Ziad
  • 1,036
  • 2
  • 21
  • 31