1

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?

1 Answer 1

2

Use Html.Action instead of Html.RenderAction

<link href="@(Html.Action("CustomStyleSheetPath)", "Shared"))" 
      rel="Stylesheet" type="text/css" />

Html.Action will return the rendered HTML in an McvHtmlString while Html.RenderAction writes directly to the response.

In MVC4 there is a new feature called conditional attributes that's why it is not working.

Because Html.RenderAction won't return anything so the attribute href won't be rendered but the other hand Html.RenderAction writes directly to the response so you get this messed up result.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That's worked perfectly. Thanks for the clarification on the difference between the RenderAction and Action

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.