How to insert jQuery code? Uncaught ReferenceError: $ is not defined in view razor code

I have the following Asp.Net MVC 4 razor code at the end of the file.

....
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

<script type="text/javascript">
    $('#Address_State').val('MA');
</script>
////// End of file

However, it generated the following html code. And it raises error at the line $('#Address_State').val('MA');. The error message is Uncaught ReferenceError: $ is not defined. How to insert jQuery code in the razor file?

.....
<script type="text/javascript">
    $('#Address_State').val('MA'); // Uncaught ReferenceError: $ is not defined
</script>
            </section>
        </div>
        <footer>
            <div class="content-wrapper">
                <div class="float-left">
                    <p>&copy; 2013 - Paperspeed</p>
                </div>
            </div>
        </footer>

        <script src="/Scripts/jquery-1.9.1.js"></script>


    <script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>


    </body>
</html>

Update:

The following is the last four lines of _Layout.cshtml.

        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)
    </body>
</html>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You need to include JQuery before you actually use it.

A common way to achieve this is in your master layout include your require scripts in the head. Or place an optional section (head) where you can conditionally include scripts

First create a required bundle for your jquery scripts you want on every page:

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/js/required").Include(
        "~/Scripts/jquery-2.0.2.js"));

    //other bundles
}

Then create a site template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Title</title>
    @Styles.Render("~/css/required")
    @RenderSection("head", false) //For css on a page by page basis
</head>
<body>
    @RenderBody()
    @Scripts.Render("~/js/required") //Here add your jquery include
    @RenderSection("scripts", false) //Here you add scripts at the bottom of the page
</body>
</html>

Then use this razor file as the base layout for all other derived razor views like this:

@{
    ViewBag.Layout = "~/Views/Shared/_MasterLayout.cshtml";
}

@section head {
     //Any css you want to add
}

<p>Some html content</p>

@section scripts {
    //scripts you want to include at the bottom on a page by page basis
}

Method 2

Move the following lines of code to the top of your _Layout.cshtml view inside of the body tag. Then the jQuery scripts will load first.

<body>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

Method 3

Your Script is called before the jquery is even loaded so it doesn’t know what $ means. Try having the jquery scripts loaded in the head section of your layout file.

Method 4

No need to move anything. Just where you have the script in the view put the script inside a section scripts like so assuming you declared a section scripts in _Layout file:

@section scripts{
    <script>
        $(document).ready(function () {
            alert('Hello');
        });
    </script>
}

you can do same technique for a section with additional CSS on each page, declare section CSS or Head or whatever name then add @section name{ } at the top of the view before the markup

Method 5

jquery add is after the render body? you will move following

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)


lines to tags

like this

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</head>

Method 6

As @Dmitri K mentions, there’s NO need to move anything around.

Just put your script that needs to be called after page load inside

$(document).ready(function () {} like so:

@section scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            // Items that NEED to be set after the page is loaded.
            $('#Address_State').val('MA');
            $('.some-div-class').on('click', 'button', function (event) 
            {
               // Binding click event to all buttons in 'some-div-class'
               // Do something on those clicks
               event.preventDefault();
               someFunction();
            }
            // And so on.
        });

        //Items that DON'T NEED to be called on page load can be put outside document.ready. For eg:
        function someFunction() { // Some logic }
    </script>
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x