a developer's notes – a semi-technical web development BLOG

January 22, 2014

JQuery doesn’t work with ASP.NET MVC 4 Application. $ is not defined

Filed under: ASP.NET MVC — Duy Nguyen @ 11:29 am
Tags: , , , , , , , ,

Why is JQuery Referenced In the Body Tag with a default ASP.NET MVC 4 Application?

In short, script loading and executing, blocks the rendering of a web page. So it is recommended to move script references in the body tag. So Microsoft decided to move the @Scripts.Render in the body tag as the default location for _Layout.cshtml. If you’re using jquery’s onReady() function in your View, make sure you declare your script tag within a scripts @section like this:

@section Scripts {
    <script type="text/javascript">

    $(function () { //Same as $(document).ready()
        alert("hello");
    });
       
    </script>
}

If you declare a traditional <script> tag outside of “@section Script{}” at either at the beginning or end of your View file, you will get an error, $ is not defined. This is because the _layout view calls @RenderBody() before the jquery script bundle.

But if you still want to declare your <script>tags and not use @section Script{}, for whatever reason, remember to comment out or delete the

@Scripts.Render("~/bundles/jquery")

reference in the body tag in the _Layout.cshtml file and move it to the head tag.

Here is a sample _Layout.cshtml.

<!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") @*--Need to move this to the <head> section otherwise you will get '$ is undefined.'*@
</head>
<body>
    @RenderBody()

    @*-- Commenting out the default location because we are not using @section Scripts {} section. By default, Microsoft added all script rendering in the <body> tag for better performance. But this will only work if you define your script tags within @section Scripts {}.*@
    @*@Scripts.Render("~/bundles/jquery")*@ 
    @RenderSection("scripts", required: false)
</body>
</html>

Advertisements

October 4, 2011

Can’t debug into a Javascript file. Error “No Disassembly Available” or “This breakpoint will not currently be hit. No symbols have been loaded for this document”

Ever put a break point in visual Studio 2010 on a .js file to get this?

This breakpoint will not currently be hit. No symbols have been loaded for this document.”

Then you decide to user the ‘debugger;’ statement. But then Visual Studio gives this error: “no disassembly available“.

You are probably loading your .js file dynamically. If you are, remove (or comment out) where you are loading and load it with an explicit script tag.

example: I was loading the script file like this:

<script src="<%=Url.StaticContent("/MyApplication/Scripts/views/script.js")%>" type="text/javascript" ></script>

I just commented out that line and hard coded the script file like this:

<script src="http://localhost/MyApplication/Scripts/views/script.js" type="text/javascript"></script>

Now I am able to user the debugger; statement AND able to put a break point in Visual Studio.

September 2, 2011

A Sample AJAX Script

Filed under: Javascript / JQuery — Duy Nguyen @ 2:51 am
Tags: , , , ,

Here is a sample AJax application. This was taken from “Ajax for Dummies”.

Here a user clicks on the “Display Message” button and it retrieves text from a text file and changes the text on the web page.

The application:


Here is the code:

<script language = “javascript”>

//Create the XMLHttpRequest object
var XMLHttpRequestObject = false;
 
if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject) { //For Internet Explorer only
    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);
}
 
//a function that takes a path for the datasource location and the div's ID to put the retrieved data into
function getData(dataSource, divID){
    if(XMLHttpRequestObject) {

        //find the div to put the data into
        var obj = document.getElementById(divID);

        //open(“method”, “URL”[, asyncFlag[, “userName”[, “password”]]])
        XMLHttpRequestObject.open(“GET”, dataSource); 

        //Set up the anonymous function to call when ready. The actual request isn't until later
        XMLHttpRequestObject.onreadystatechange = function() 
        {   
            //readState[ 0:uninitialize, 1:loading, 2:loaded, 3:interactive, 4:complete ]
            //status 200 = OK
            if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                //data retrieved sucessfully so put the retrieved data into the div
                obj.innerHTML = XMLHttpRequestObject.responseText;
            }
        }
       
        //request server for data. And the anonymous function will handle the response back from the server
        XMLHttpRequestObject.send(null); //null is only used for GETs
    }
}

</script>
 
<body>
 
<H1>Fetching data with Ajax</H1>
    <form>
        <input type = 'button' value = 'Display Message' onclick = 'getData(‘http://localhost/ch01/data.txt’,‘targetDiv’)'>
    </form>
 
    <div id='targetDiv'>
        <p>The fetched data will go here.</p>
    </div>
 
</body>

The text file data.txt, contains:

This text was fetched using Ajax.

I hope this was simple enough. The interesting thing about this is that the function to handle the response is setup before the actual request call. Enjoy!

Blog at WordPress.com.