简体   繁体   中英

How to include JavaScript from a Partial View in ASP.NET MVC3

I would like to be able to provide a way for partial views to include JavaScript code / files at the bottom of a view. This would enable partial views to include any JavaScript files that they depend on. For instance, if I wanted to write a partial that needs to create a JQueryUI dialog, I would like to import the JQueryUI JavaScript file as well as add JavaScript code that renders the dialog.

I'm currently writing this code in the parent view, which makes it kind of pointless to use a partial view.

I understand that calling RenderPartial multiple times would result in scripts being included multiple times. This is a solvable issue once I know how to actually include JavaScript into the main view from the partial view.

Define ContentPlaceHolder in your MasterPage (ASPX) or Section in your Layout Page (Razor)

ASPX :

<body>
  <!-- End of Body -->
  <asp:ContentPlaceHolder ID="JavaScriptIncludes" runat="server" />
</body>

Razor :

<body>
  <!-- End of Body -->
   @RenderSection("JavaScriptIncludes", required: false)
</body>

Then in the Partial:

ASPX :

<asp:Content ID="ExtraJs" ContentPlaceHolderID="JavaScriptIncludes" runat="server">
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")" />
</asp:Content>

Razor :

@section JavaScriptIncludes
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")" />
}

Also think about using a HTML Helper to render out the <script> tags.

Here is how you can have Partial View with JavaScript code that uses any library ( even when libraries are loaded at the end of the page )

In your partial view add:

@{
    TempData["Script"] += "MyFunction();";
}

<script type="text/javascript">
    function MyFunction() {
        // you can call your library here, e.g. jquery:
        $(function () {

        });
    }
</script>

In your _Layout.cshtml page add after your libraries included:

@*LOAD YOUR LIBRARIES HERE (E.G. JQUERY) *@


@if (TempData["Script"] != null)
{
    <script type="text/javascript">
        @Html.Raw(TempData["Script"].ToString())
    </script>
}

You can have multiple partial views attaching theirs functions to the same key TempData["Script"]. They will happily coexist if you keep adding the functions using += operator:

@{
    TempData["Script"] += "AnotherFunction();";
}

您可以在<body>标记内包含<script>标记,以便在局部视图中包含它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM