Search code examples
asp.netasp.net-mvcmaster-pages

Render master page element based on child page


In MVC one can use in _Layout.cshtml:

@if (IsSectionDefined("styles"))
{@RenderSection("styles", required: false)}

together with @Section styles on content page / layout to include css styles within <head> if given section is needed.

Is there an efficient way to mimic the same behaviour in Web Forms?

To summarise: I would like to have a possibility to render css and js on master page, only if they are required by specific child page based on that master page. So it will be not be included on pages which do not require those css and js files.


Solution

  • You could use ContentPlaceHolder. In your master page, define a content place holder as follows:

    <head runat="server">
        <title>..</title>
        <meta charset="utf-8"/>
        ..
        <asp:ContentPlaceHolder ID="head" runat="server">
        </asp:ContentPlaceHolder>
    </head>
    

    ..and those child pages that require a special css or js files can use this content place holder to inject their needed files, e.g.:

    <%@ Page Title="" Language="C#" MasterPageFile=".." AutoEventWireup="true" CodeBehind=".." %>
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
        <link href="some css file dedicated only to this child page" rel="stylesheet" />
        <script src="..js.."></script>
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
        ..
        <h1><asp:Label ID="lblPageTitle" runat="server" Text=""></asp:Label></h1>
        ..
    </asp:Content>