1

I am working with MVC 5.

I need to call a function before every page is loaded. I did it in the _Layout.cshtml view:

 $(function () {
        $('body').on('click', function (e) {
            var valor = GetSession();
            $('#hdnSessionTime').val(valor);
        });
}

I save a value in a hidden field defined in the layout page, and every time the user click on every page, the function called GetSession executes.

The problem is that it execute after @RenderBody() and I need it before...

Is that possible?

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
Diego
  • 2,238
  • 4
  • 31
  • 68
  • RenderBody() load a page and all the functionality of the site. What I am trying to do is that when the users Clicks on an element of the page, and it calls another page or a Partial View, that "click' execute after the function defined in _layout.cshtml, and not before... Thanks – Diego Aug 18 '17 at 17:25

1 Answers1

1

Sometimes you want to perform logic either before an action method is called or after an action method runs. To support this, ASP.NET MVC provides filters. Filters are custom classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods. You can use custom filter like this.

Client Side

If you want to run code in client side, you can use this code (before @RenderBody()):

<script type="text/javascript">
    $(document).ready(function () {
        var valor = GetSession();
        $('#hdnSessionTime').val(valor);
    });
</script>

see this for similar example.

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55