ASP.NET MVC - Referencing stylesheets in the master page

asp.net-mvc, master-pages, visual-studio

Solution

Try this technique - include your stylesheet both ways. Include one with a fixed path reference that Visual Studio will use for design-time support, but enclose it in server-side comments so it's not actually included during run-time. The second reference is the "real" reference used at run-time, and with Url.Content() it'll work whether your app is a sub directory or not.

<% /* %> 
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> 
<% */ %>

<link href="<%=Url.Content("~/Content/Site.css") %>" rel="stylesheet" 
      type="text/css" />

Problem

I have a master page that is in /Views/Shared. The master page references a stylesheet in the `/Content` folder. Everything works fine if I reference the stylesheet using `"../../Content/style.css"`. However, my web application is not in the root folder in our production environment, so the relative path doesn't work. I have tried "<%=ResolveUrl("~/content/style.css") %>" which does work in the production scenario, but then the designer in Visual Studio complains about my classes being wrong (and I cannot preview the page with CSS in the design tab). Is there a solution that makes this work in both situations? I accomplished this in WebForms by writing server-side code that reset the link tag. I could do that here, but I would like to avoid it.

Original source