Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Eskil Busck 3 posts 33 karma points
    Nov 01, 2013 @ 13:09
    Eskil Busck
    0

    Setting default content of a section (MVC)

    I'm having troubles finding out how to set the default content of a section when working with MVC Views.

    I have a master template called _Layout.cshtml, where I have a section called @RenderSection("header",false). In most of my templates, I just want the content to be inherited from the master, but in a few I would like to modify it.

    Before working with views I would have done it like this.

    Master:

    <asp:ContentPlaceHolder ID="header" runat="server">
      <!-- Default content -->
    </asp:ContentPlaceHolder>
    

    Page template:

    <asp:Content ContentPlaceHolderID="header" runat="server">
      <!-- Alternate content -->
    </asp:Content>  
    

     


    How's that achieved when working with Views?

     

  • Dan Lister 416 posts 1973 karma points c-trib
    Nov 01, 2013 @ 16:42
    Dan Lister
    101

    I think this blog post should explain a solution to your problem. The first solution being to check if a child section has been defined...

      @if (IsSectionDefined("Footer")) {
          RenderSection("Footer");
      }
      else { 
          This is the default yo!   
      }
    
    

    And the second being a custom helper method which accepts some default content...

    public static class Helpers {
      public static HelperResult RenderSection(this WebPageBase webPage, 
          string name, Func defaultContents) {
        if (webPage.IsSectionDefined(name)) {
          return webPage.RenderSection(name);
        }
        return defaultContents(null);
      }
    }
      @RenderSection("Footer", @This is the default!)
    
  • Eskil Busck 3 posts 33 karma points
    Nov 01, 2013 @ 23:46
    Eskil Busck
    0

    Thanks!

    I don't get the second part, but the first is working, so I'm happy :)

    - E 

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies