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 PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title><asp:ContentPlaceHolder ID="Title" runat="server" /></title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <link rel="Stylesheet" type="text/css" href="/layout.css" />
        <asp:ContentPlaceHolder ID="Head" runat="server" />
    </head>
    <body>
      ...
    </body>
</html>

The Page

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" MasterPageFile="~/Views/Shared/Site.Master" %>

<asp:Content ContentPlaceHolderID="Title" runat="server">
    This is my page!
</asp:Content>

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

Yep…it’s that easy!