How to make a script run only once?

Asked

Viewed 1,006 times

2

I’m using Asp.net MVC

In my layout I have a menu div

and I have the container div where my @RenderBody()

And downstairs I have a script that pays for my menu:

 $(document).ready(function (e) {
        $(".Menu").each(function (index, item) {
            var url = $(item).data("url");
            if (url && url.length > 0) {
                $(item).load(url);
            }
        });
    });

But when clicking on other pages, it is always calling this script

I thought that by using @RenderBody he just gave a "refresh" just in the div that he is

  • @Renderbody is equivalent to PHP include. It’s just a way to reuse snippets of code. To update only a specific div it would be necessary to use Ajax

1 answer

1

@Rod the script that sits in the layout runs on all pages that use the layout, to do this singularly try to put the script inside the View.

It would look like this in the view:

@section scripts{
<script type="text/javascript">
// Aqui dentro seu codigo
</script>
}

Updated: You can also set up a helper to call up the menu on all pages .Create a Menuhelper.cshtml file and declare:

@helper NomeDoMetodo(){
 // Código cshtml...
}

Then on the layout put:

 @RenderSection("MenuHelper", false)

And finally just call him at the View:

@section Menu{
    @MenuHelper.NomeDoMetodo()
}
  • 1

    As it is to assemble the menu, doing so it will assemble every time calling a view, will continue doing the same thing, =/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.