2

I was working on MVC-3 web application. Now i changed it to mvc4 and put the jquery files in end of _Layout page

<html>
<head>
</head>
<body>
    @Html.Partial("_Menu")
    @RenderBody()
    @System.Web.Optimization.Scripts.Render("~/jquery")
</body>
</html>

I have used some jquery in Partial View "_Menu", in Mvc 3 this is working fine because i put jquery files in head tag but now i am facing issue when i call this partial view

Uncaught ReferenceError: $ is not defined

I think this problem is due to jquery files are loading at the end of the page. Solution that comes in my mind is to load jquery files on head tag but i don't want to do this.

Suggest me any other solution. How can i use jquery in partial view.

Thank You

Shoaib Ijaz
  • 5,347
  • 12
  • 56
  • 84
  • You're right, that's the problem. Just move `@System.Web.Optimization.Scripts.Render("~/jquery")` in `` and you'll be just fine. – Andrei V Feb 21 '14 at 08:05
  • @AndreiV Any Other way is possible for this problem? – Shoaib Ijaz Feb 21 '14 at 08:07
  • 1
    @AskQuestion you can always put the javascript logic in a separate file and include the file after the jquery initialization. – ssimeonov Feb 21 '14 at 08:10
  • 2
    It's really not possible to use something before you declare it. This is a general rule in programming (except for some languages that "auto declare" the variables). There is no other way of using it. – Andrei V Feb 21 '14 at 08:11

4 Answers4

2

You can't use Section in partial views, but you can write an extension to do the same:

   public static class ScriptBundleManager
{

    private const string Key = "__ScriptBundleManager__";

    /// <summary>
    /// Call this method from your partials and register your script bundle.
    /// </summary>
    public static void Register(this HtmlHelper htmlHelper, string scriptBundleName)
    {
        //using a HashSet to avoid duplicate scripts.
        var set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet<string>;
        if (set == null)
        {
            set = new HashSet<string>();
            htmlHelper.ViewContext.HttpContext.Items[Key] = set;
        }

        if (!set.Contains(scriptBundleName))
            set.Add(scriptBundleName);
    }

    /// <summary>
    /// In the bottom of your HTML document, most likely in the Layout file call this method.
    /// </summary>
    public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
    {
        var set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet<string>;

        return set != null ? Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", set.ToArray()) : MvcHtmlString.Empty;
    }


}

Then in _Layout file, after the end of your script bundles:

@Html.RenderScripts()

Then at the top in your partial view:

@{Html.Register("~/bundles/group_of_relevant_js_files_for_partial_view");}

Then all your required functionality will load after jQuery is defined.

However: note that Kendo js files need to be loaded prior to use of their controls/extensions...so they always need to be at the top of your layout file...that's wacky, but that's life...

Robert Achmann
  • 1,986
  • 3
  • 40
  • 66
2

If you put the jQuery code in an external script file then you can take advantage of the defer attribute for the script element as follows:

<script type="text/javascript" src="<path to your .js file>" defer></script>

So your partial view would include this script tag and 'defer' stops the browser from running the script until after the page has loaded, which means that the jQuery libraries will exist when it executes.

Christopher King
  • 1,691
  • 23
  • 28
1

if you always load the menu in the _Layout file and the jQuery should always be there, then you could just write the jQuery code in the _Layout page at the bottom.

If your jQuery uses the model from the _Menu, then you could create a helper like this

EDIT

If you follow the link I mentioned, it shows how to define some sort of section in your partial view, then rendering those scripts in the _Layout.

Community
  • 1
  • 1
devqon
  • 13,818
  • 2
  • 30
  • 45
  • No, I have mentioned just one scenario. I am using partial views in other pages as well so i have to move all scripts to main pages from partial views. This will be extensive work for me – Shoaib Ijaz Feb 21 '14 at 09:03
  • That is why I suggested the second answer, to create a helper that allows you to include a script 'section' in your partial view. Check out http://stackoverflow.com/questions/5433531/using-sections-in-editor-display-templates/5433722#5433722 – devqon Feb 21 '14 at 09:25
-3

Add section "Scripts" at the end of your Layout file and after including jQuery. Then, always put your scripts into this section. That's it.

  • 4
    You cannot use sections in PartialViews – ssimeonov Feb 21 '14 at 08:13
  • This doesn't work if, for example, in your `_Layout`'s `` you write `$(document).ready(function(){})`. You are then referencing something which _has not been yet defined_. – Andrei V Feb 21 '14 at 08:20