user1321237
user1321237

Reputation:

How can I simplify adding many of the same javascript files in my MVC3 Razor view?

In my MVC3 application I have many different screens and these all use a master layout. Seven of the screens all use the same code such as that below:

<script src="@Url.Content("~/Scripts/x/tiny_mce.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/y/ajaxOnFailure.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/y/tinyMCEOptions.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/z/updateField.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/z/gridClick.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/z/createDialog.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/a/dialogSuccess.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/a/refreshGrid.js")" type="text/javascript"></script>

I would like to have some way of putting all of these lines into an external file and then have them added.

is there some way I can have one file which I add to my razor view and inside that file imports all the javascript files above?

Upvotes: 1

Views: 124

Answers (5)

Max
Max

Reputation: 3328

You should definitively check out the bundling and minification features which aims at simplification of these things and also will have your page load and render much much faster.

http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

This feature, by itself, is a good reason to move up to MVC 4.

Upvotes: 0

RubbleFord
RubbleFord

Reputation: 7636

I use Combres very good script combiner and minifier its available on nuget.

Upvotes: 2

Maess
Maess

Reputation: 4146

Use a second layout that implements your master layout, but imports the scripts you need for your 7 views: A->B->views 1-7.

Upvotes: 0

Nolan St. Martin
Nolan St. Martin

Reputation: 407

You could add them to a PartialView, then include the PartialView in the pages you want the scripts to show up on.

Upvotes: 0

Yorgo
Yorgo

Reputation: 2678

you can create a new .cshtml file and impot all files inside that

/Views/Shared/Scripts.cshtml

and then add this to your view

@Html.Partial("Scripts")

Upvotes: 1

Related Questions