0

if I have an Asp.net / MVC project that contains a _layout.cshtml page, where do I include javascript that I want to use on a single view please?

I don't want to put it in the layout as it really will be for one view.

Is it ok to put the tags in my view bearing in mind that's the middle of the rendered page?

Thanks for any help. Cheers.

tombola
  • 73
  • 2
  • why could you not use a @Scripts.Render("~/bundles/mybundle") in your nested cshtml? – ale Dec 01 '14 at 16:12
  • possible duplicate of [MVC 4 - Where to load JS Scripts](http://stackoverflow.com/questions/14784616/mvc-4-where-to-load-js-scripts) – MikeSmithDev Dec 01 '14 at 16:54

4 Answers4

4

It will work fine even if it's in the middle of the rendered page, but a better option is to put it in a scripts section.

In the view:

@section scripts
{
    <script>
        // Your script
    </script>
}

In the layout, wherever you want the scripts to go in the rendered page:

@RenderSection("scripts", required: false)
Sam
  • 4,994
  • 4
  • 30
  • 37
0

You could put a script tag on that View. Although that might not be MVC of doing things....

0

You most likely can place it directly in your view, but a common approach is to define an "additional scripts" section in your layout, and then just add to it from whatever view, like so...

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

Community
  • 1
  • 1
SethMW
  • 1,062
  • 1
  • 9
  • 10
0

Or you can use Unobtrusive pattern (http://en.wikipedia.org/wiki/Unobtrusive_JavaScript)

Using an observer on ajaxStop event and load event for chek if the view has the elements on which you have to call that javascript

hayatoShingu
  • 418
  • 5
  • 11