In your master page create the following placeholder inside the <head>
section.
Master page
<asp:ContentPlaceHolder ID="HeadContent" runat="server"></asp:ContentPlaceHolder>
Then inside your controller you should determine the list of .css files to be used as well as create a string that the views can use to easily place the content inside the page. Here is what I've used.
Controller
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
List<string> css = new List<string>()
{
"one.css",
"two.css",
"three.css",
"four.css"
};
IList<string> cssTags = new List<string>();
StringBuilder cssTag = new StringBuilder();
css.ForEach(c =>
{
cssTag.AppendLine(string.Format(@"<link href=""{0}"" rel=""stylesheet"" type=""text/css"" />", HttpUtility.HtmlEncode(c)));
});
ViewData["css"] = cssTag.ToString();
return View();
}
Then inside your view just place the follwing
View
<asp:Content ID="headContent" ContentPlaceHolderID="HeadContent" runat="server">
<%= ViewData["css"] %>
</asp:Content>
The reason why I build up the list of .css inside the controller and then create a string that the view uses, is because I want the views to be as stupid as possible. An option would be to just place the list of .css files into the ViewData
itself and then let the view do the looping and create the link
tag, but it's better to do it elsewhere if possible.
Another option to using ViewData
is to use a strongly typed view with a string property and then the view just picks that guy off. I personally don't use the ViewData
dictionary. Instead all my views are strongly typed.