Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 Razor - Use script references in Layout page from Partial View

I used some jquery in my partial view and realised that I need to have the script reference put in the partial view Again in order for the jquery to works.

I wonder is there any method which I can "call" all the script references in the Layout page so I dont need to duplicate it in the Partial View??

I tried to search for related information and tried to use @section to store the script references, but it seems cant work.

Hope can get some guide here... Appreciate it...

like image 264
shennyL Avatar asked Jul 26 '11 07:07

shennyL


People also ask

Can we use script in partial view?

A Note About Script Binding for Partial ViewsJavaScript 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 you reference partial view?

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.

Where do you put JavaScript on a Razor page?

A JS file for the Index component is placed in the Pages folder ( Pages/Index. razor. js ) next to the Index component ( Pages/Index. razor ).


2 Answers

You can put all your script references in a Partial View of its own, and then call @Html.Partial("ScriptReferences") from both the Layout page and the other Partial View that needs the script references.

like image 50
MartinHN Avatar answered Oct 18 '22 07:10

MartinHN


I normally include/reference all the scripts in my layout view. Although some are not needed on all pages.

The partial views, do not have to worry about a script not available. And it also saves time during development.

The overhead of having all scripts available is minimal. Specially if you merge all .js files in one big minimized script (Chirpy can do that for you). Modern browsers will know it's the same script and not download and parse them over and over.

like image 22
GvS Avatar answered Oct 18 '22 08:10

GvS