Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 985
Jonathan Matheus Avatar asked Jan 16 '11 20:01

Jonathan Matheus


People also ask

Can you put JavaScript in a partial view?

JavaScript functions can be bound to elements on the partial view; the partial view is rendered at the same time as the parent view. This happens when loading the partial view with a @Html. Action helper method, as in this section from Edit.

How do I render a partial part of a view?

Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .

Can you use the View () method to return a partial view how?

To create a partial view, right-click on view -> shared folder and select Add -> View option. In this way we can add a partial view. It is not mandatory to create a partial view in a shared folder but a partial view is mostly used as a reusable component, it is a good practice to put it in the "shared" folder.

Can we use jQuery in partial view?

Partial helper functions will not work with jQuery Client Side scripting. The Partial View will be populated and fetched using jQuery AJAX and finally it will be rendered as HTML inside DIV using jQuery.


1 Answers

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.

like image 133
RPM1984 Avatar answered Sep 21 '22 15:09

RPM1984