[SOLVED] 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 {

<script type="text/javascript">
////// 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
            <div class="content-wrapper">
                <div class="float-left">
                    <p>&copy; 2013 - Paperspeed</p>

        <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>



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

        @RenderSection("scripts", required: false)


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(

    //other bundles

Then create a site template:

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

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

Answered By – gdp

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *