4

I have my ASP.NET MVC project. I have a _Layout, a controller, and some views. Some of the code is obviously global. For example _Layout CSS and CSS that is common across the site would definitely go in a global css file.

But when styles and JavaScripts are specific to a view should they be included in the .cshtml file or should they go in a global file?

user3929962
  • 517
  • 3
  • 6
  • 23
  • 3
    Note that CSS and JS that is coded directly in a `.cshtml` won't be bundled and minified. – dee-see Sep 25 '14 at 15:30
  • 1
    Inline JS and CSS as well as those that are put in the `.cshtml` file is *usually* frowned upon since a) it would not be bundled/minified as said above, b) typically not cached and c) makes troubleshooting styling and JS errors a little more difficult as you now have multiple places to check/track. – Tommy Sep 25 '14 at 15:37
  • Sometimes It will make sense to have a small amount of js/css in html, however it's very case depending and there's way too much element need to be considered. Can you explain in detail about your situation as much as you can: 1)amount of js/css globally 2)amount of js/css specific for page 3)Scale of the application 4)Capability of your server end hardware 5)CDN/Proxy in use? 6)Usual user behavior(like how many page(s) they need to go through for a single time use) – tweray Sep 25 '14 at 16:58

3 Answers3

0

you can define a section via RenderSection in layout and then use that in your view like this :

_Layout.cshtml :

<head>
<title>@ViewBag.Title</title>
<meta name="viewport" content="width=device-width" />
<script src="~/Content/Scripts/public.js"></script>
@RenderSection("head", false)
</head>

Post.cshtml :

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
 }
@section head{
<script src="~/Content/Scripts/custom.js"></script>
}
0

In this way the view specific resources are bundled and minified

_Layout.cshtml:

<head>
    @Styles.Render("~/Content/mastercss")
    @Scripts.Render("~/bundles/masterjs")

    @RenderSection("header", required: false)
</head>

View :

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
 }

@section header{
    @Styles.Render("~/Content/viewspecific")
    @Scripts.Render("~/bundles/viewspecific")
}

Bundles should be partitioned by pages that need them. For example, the default ASP.NET MVC template for an internet application creates a jQuery Validation bundle separate from jQuery. Because the default views created have no input and do not post values, they don't include the validation bundle

http://www.asp.net/mvc/overview/performance/bundling-and-minification

0

The things that are common to all views should be included in the _Layout file. The CSSs and the Javascript that is custom for a certain page should be loaded just on that certain page.(Not written, but rendered from different .JS or css files)

brainfood
  • 219
  • 1
  • 9