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.

2
  • why could you not use a @Scripts.Render("~/bundles/mybundle") in your nested cshtml? Commented Dec 1, 2014 at 16:12
  • possible duplicate of MVC 4 - Where to load JS Scripts Commented Dec 1, 2014 at 16:54

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant. Thanks everyone for the replies.
0

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.