Search code examples
asp.net-mvc-5sitefinity

In Sitefinity 11 - Possible to generate custom html/script to html section or tag in base template via MVC widget


I guess I should start by mentioning that I am relatively new to both Sitefinity and MVC, and I appreciate your help. My research thus far on this topic has came up empty.

So, we'd like to place custom html and or script at the end of the body tag on our webpages via a widget we can drop onto a specific page or page template. I am open to any suggestions for accomplishing this, but what I have been attempting thus far, is to do this via references placed on our custom base template.

In the .cshtml, I notice by default Sitefinity has @Html.Section("head"), @Html.Section("top"), and @Html.Section("bottom"). Is there a way I can write directly to this "bottom" section from an MVC widget or view?

I have attempted the above, and other approaches such as using RenderSection in the base layout:

@if (IsSectionDefined("MyOtherJavascript"))
{
   @RenderSection("MyOtherJavascript");
}

and then in the widget view:

@section MyOtherJavascript 
{
   <script type="text/javascript">
     // some code
   </script>
}

but when I do this I get an error such as:

[layoutname].cshtml" cannot be requested directly because it calls the "IsSectionDefined" method.

Thanks for any insight you can provide.


Solution

  • One way to approach this is to create a new "placeholder area" in your master layout cshtml file right above the closing body tag.

    Example:

    <body>
    @Html.SfPlaceHolder("Header")
    @Html.SfPlaceHolder("Main")
    @Html.SfPlaceHolder("Footer")
    
    @Html.SfPlaceHolder("BeforeClosingBody")
    </body>
    

    This will create a draggable area in Sitefinity page edit mode, so you could drag any widget you want into this area, including a Content Block widget (for any arbitrary html) or the Javascript widget (for any js code).

    More details about sfPlaceHolder in the official documentation.