I'm taking a break from my umbrella series in an effort to contribute to society, instead of distracting it!
I really wanted to like ASP.NET MVC Sections... but I just couldn't. They just seem so rigid.
Orchard [a popular CMS engine I've talked about before] has the Script.Head() and Script.Foot() methods, and these seemed like a big improvement. You could add code to these anywhere, and as many times as you liked. Unfortunately, while it is a step in the right direction, it still isn't quite dynamic enough. It only allows two sections: the head and the foot (and not to mention the application has to be built within Orchard). So yet again, even though these Orchard helpers are good, they aren't good enough.
Piggybacking of off some other solutions, I was able to create something that gave me everything I wanted:
- Unlimited sections.
- No restriction on the number of codes blocks that could be added to a section.
The source code is hosted on GitHub, so I won't reproduce it here, but I will show you how easy it is to use.
In your layout View, or wherever you want the section to be rendered, include the following code:
<!DOCTYPE html> <html lang="en"> <head> <title>@ViewBag.Title</title> @this.Section("header") </head> <body> @this.Section("prebody") @RenderBody() @this.Section("footer") </body> </html>
Then, to add content blocks to your sections:
That's it and that's all! There are some improvements that could be made, like a parameter to order the content added to a section, but even in its basic form, I hope it's helpful!
Available as a NuGet package!