Sunday, December 23, 2012

Microsoft JScript runtime error: '$' is undefined in MVC4 Mobile Web Application

I came across this problem while I was developing a mobile web application in MVC4. I think most of you all have faced this issue and found a solution as well. But I thought it was worth to share this, becuase this did the trick for me.
In my MVC4 web application , I had my _Layout.cshtml page like this.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title</title>
        <meta name="viewport" content="width=device-width" />
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        @Styles.Render("~/Content/mobileCss", "~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div data-role="page" data-theme="b">
            <div data-role="header">
                @if (IsSectionDefined("Header")) {
                    @RenderSection("Header")
                } else {
                    <h1>@ViewBag.Title</h1>
                    @Html.Partial("_LoginPartial")
                }
            </div>
            <div data-role="content">
                @RenderBody()
            </div>
        </div>

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

But inorder to resolve the error, I had to modify the page like below.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title</title>
        <meta name="viewport" content="width=device-width" />
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        @Styles.Render("~/Content/mobileCss", "~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        @Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")
     
    </head>
    <body>
        <div data-role="page" data-theme="b">
            <div data-role="header">
                @if (IsSectionDefined("Header")) {
                    @RenderSection("Header")
                } else {
                    <h1>@ViewBag.Title</h1>
                    @Html.Partial("_LoginPartial")
                }
            </div>
            <div data-role="content">
                @RenderBody()
            </div>
        </div>
     
        @RenderSection("scripts", required: false)
    </body>
</html>

Note that I changed the place of JQuery script line from section <body> to <head>.
source : http://forums.asp.net/t/1835597.aspx/1

1 comment:

  1. Man, this fix should have been officially posted by MS. Fixed my issues with jQuery as well.

    ReplyDelete