How to make a script run only once?

2

I'm using Asp.net MVC

In my layout I have a menu div

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

And below I have a script that rendeniza 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 you click on other pages, it is always calling this script

I thought that by using @RenderBody it just gave a "Refresh" only in the div that it is

    
asked by anonymous 03.09.2014 / 16:00

1 answer

1

@Rod The script that stays in the layout runs on all pages that use the layout, to do this uniquely try putting 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 mount a helper to call the menu on all pages . Create a MenuHelper.cshtml file and declare:

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

Then in the layout put:

 @RenderSection("MenuHelper", false)

And finally just call it in View:

@section Menu{
    @MenuHelper.NomeDoMetodo()
}
    
03.09.2014 / 16:08