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

4
  • You're right, that's the problem. Just move @System.Web.Optimization.Scripts.Render("~/jquery") in <head> and you'll be just fine. Commented Feb 21, 2014 at 8:05
  • @AndreiV Any Other way is possible for this problem? Commented Feb 21, 2014 at 8:07
  • 1
    @AskQuestion you can always put the javascript logic in a separate file and include the file after the jquery initialization. Commented Feb 21, 2014 at 8: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. Commented Feb 21, 2014 at 8:11

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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...

Comments

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.

2 Comments

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
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 stackoverflow.com/questions/5433531/…
-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.

2 Comments

You cannot use sections in PartialViews
This doesn't work if, for example, in your _Layout's <head> you write $(document).ready(function(){}). You are then referencing something which has not been yet defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.