1

In my MVC3 solution, I am attempting to implement the solution in this answer to dynamically add a CSS reference to the _Layout.cshtml file from within a partial view.

Here is a snippet of my _Layout file:

<!DOCTYPE html>
<html>
<head>

@Html.RenderStyles()

</head>

<body>
    <div id="header-wrapper">
        @Html.Action("Header", "Shared")
    </div>

    <div class="container">
        @RenderBody()
    </div>

    @RenderSection("scripts", required: false)
</body>

</html>

and in the partial view (that is rendered by the @Html.Action("Header", "Shared") bit):

@{
    Html.AddStyle(Model.Company.CSSPath);
}

While the HtmlExtension methods are working as expected, it seems that the events are occuring in the incorrect order.

The @Html.RenderStyles() in the _Layout head is occuring before the Partial View has time to add the CSS file to the Styles. I was under the impression that Partial Views were rendered before the _Layout.

I'm guessing that the cause has to do with the fact that I'm rendering my Partial View with an Html.Action call. If I don't do so, however, then how can I populate the Partial view with its desired model?


Per Matt Razza's comment, if I were to render the partial view the "normal way" using: @Html.Partial("ViewName", model) I'm then required to give my _Layout a Model and then force all other models to inherit from that Model? Is that truly the best option?

Community
  • 1
  • 1
skeryl
  • 5,225
  • 4
  • 26
  • 28
  • Don't you want `@Html.Partial("ViewName", model)`? I don't understand why you're using `Action`. – Matt Razza Nov 25 '13 at 00:14
  • Because my _Layout has a different model than the partial view. I'm not sure what merging the models will do to the application, but it's certainly a possibility. I will let you know – skeryl Nov 25 '13 at 00:18
  • When I add a model to my _Layout view and render the header in that way, it then requires that all of my models are of that same type (which is not realistic at all) – skeryl Nov 25 '13 at 00:24
  • It wouldn't make sense to have an instance of the partial view model as a member of the parent model? `@Html.Partial("ViewName", model.PartialModel)` – Matt Razza Dec 02 '13 at 23:49
  • @MattRazza, I could do that. The only problem with that is that every one of my models in the entire application would have to contain that partial model. Yes, I could force them to extend some sort of base model class. But what happens when someone adds a model to the application without extending the base class? Or, what happens if the data for that partial model doesn't get populated completely from within that model? – skeryl Dec 03 '13 at 04:33
  • The point is that it seems like a lot of work (and a lot of added complication) just for a dynamic CSS file. – skeryl Dec 03 '13 at 04:39

0 Answers0