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

前端 未结 5 1906
执念已碎
执念已碎 2020-12-31 06:54

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

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



        
5条回答
  •  别那么骄傲
    2020-12-31 07:13

    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:

    
    
    
        
        Title
        @Styles.Render("~/css/required")
        @RenderSection("head", false) //For css on a page by page basis
    
    
        @RenderBody()
        @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
    }
    
    

    Some html content

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

提交回复
热议问题