Including External JavaScript and CSS Stylesheets in a .NET Page

I’ve seen several ASP.NET developers architect their web apps so that the only way they can include page-specific CSS or JavaScript is via the code-behind file. That is a bad method because you generally want to keep as much display logic in the aspx as possible. It is actually very easy to structure your master page to allow page-specific CSS/JavaScript. You’ll kick yourself when you see this:

The Master Page

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><asp:ContentPlaceHolder ID="Title" runat="server" /></title>
    <link rel="stylesheet" href="/layout.css" />
    <asp:ContentPlaceHolder ID="Head" runat="server" />
</head>
<body>
    <asp:ContentPlaceHolder ID="Body" runat="server" />
</body>
</html>

The Page

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" %>

<asp:Content ContentPlaceHolderID="Title" runat="server">
    My Page Title
</asp:Content>

<asp:Content ContentPlaceHolderID="Head" runat="server">
    <link rel="stylesheet" href="/css/home.css" />
    <script src="/scripts/home.js"></script>
</asp:Content>

<asp:Content ContentPlaceHolderID="Body" runat="server">
    <h1>Welcome to My Page!</h1>
    <p>This is where your main content will go.</p>
</asp:Content>

Yep…it’s that easy!