Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding scripts in MVC

I am starting with first MVC application. Here i have the basic confusion. Actually the default _Layout.cshtml file created like below

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <script>

    </script>
    @RenderBody()

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

I used basic template so not have any template. But check the '@Scripts.Render("~/bundles/jquery")' line. Its after the @RenderBody(). So it actually it adds after the body section.

I think this is actually the best practice. But if i add $.(document).ready it shows the following error

Microsoft JScript runtime error: '$' is undefined

Based on the error, it because of script tag. I just moved the '@Scripts.Render("~/bundles/jquery")' line before @Render body and the final page like

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")

</head>
<body>
    <script>

    </script>
    @RenderBody()      
    @RenderSection("scripts", required: false)
</body>
</html>

The applicationw works fine with my jquery.

So why this is happened? So always the script adding tag need before @RenderBody ? Then why default template showing in wrong location?

like image 468
Akhil Avatar asked Mar 24 '14 08:03

Akhil


People also ask

How can you include scripts in an MVC application?

Go to Views -> Shared -> _Layout. cshtml file and add the render code. Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.

How do I bundle a script in MVC?

In an ASP.NET MVC project, the BundleConfig class in the App Start folder can be used to generate style or script bundles. This method has a parameter bundle, which is of the type BundleCollection. At the start of the program, all of the bundles created are added to this bundle parameter.

Can we add script in body?

Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.


1 Answers

This probably happens because you are adding the scripts before the jQuery reference in the page. You need to write scripts inside scripts section in your views:

@section scripts {
    //stuff
}

This will make sure it will be rendered after the jQuery reference(RenderSection call).

like image 81
Ufuk Hacıoğulları Avatar answered Oct 13 '22 19:10

Ufuk Hacıoğulları