I have a problem getting my layout.cshtml to have a dynamically chosen CSS file based on some business logic.
In my layout.cshtml I have the following in my head section:
<head>
<link href="@{Html.RenderAction("CustomStyleSheetPath", "Shared");}" rel="Stylesheet" type="text/css" />
</head>
In my ‘Shared’ Controller, I have:
[ChildActionOnly]
public virtual string CustomStyleSheetPath()
{
string customCssPath = GetCssPath(); // e.g. "css/customStyleSheet.css"
return customCssPath;
}
When I display the page, the css not pulled in correctly and I have the following when I view source:
<head>
<linkcss\customStyleSheet.css href="" rel="Stylesheet" type="text/css" />
</head>
This code used to work in MVC 3 so I’m wondering what I’m doing wrong?
Use
Html.Actioninstead ofHtml.RenderActionHtml.Actionwill return the rendered HTML in anMcvHtmlStringwhileHtml.RenderActionwrites directly to the response.In MVC4 there is a new feature called conditional attributes that’s why it is not working.
Because
Html.RenderActionwon’t return anything so the attributehrefwon’t be rendered but the other handHtml.RenderActionwrites directly to the response so you get this messed up result.