How Can I Have View-Specific <head> contents Using Asp.Net MVC 3 and Razor?

前端 未结 2 767
小鲜肉
小鲜肉 2021-01-31 09:06

I want to link a specific style sheet in certain Views in addition to what already gets linked in _Layout.cshtml. For non-Razor, I see using the content place holder. How woul

2条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 09:31

    The equivalent of content placeholders in Razor are sections.

    In your _Layout.cshtml:

    
    @RenderSection("Styles", required: false)
    
    

    Then in your content page:

    @section Styles {
        
    }
    

    An alternative solution would be to put your styles into ViewBag/ViewData:

    In your _Layout.cshtml:

    
        @foreach(string style in ViewBag.Styles ?? new string[0]) {
            
        }
    
    

    And in your content page:

    @{
        ViewBag.Styles = new[] { "~/Content/StandardSize.css" };
    }
    

    This works because the view page gets executed before the layout.

提交回复
热议问题