Using blocks in both MVC and Webforms context made easy in #Episerver
This is a great feature. Comes in handy when you need to convert your site from webform to MVC, it allows the editor to reuse the blocks, just by adding partial views (MVC renderers).
Published 14th December 2016
For Episerver Version 7.5 and later
Johan Björnfot: You cannot mix Mvc and webform templates on the same request. For example a page rendered through a MVC controller/View cannot render a block that only has a UserControl template. So to be able to use a block both on a webform page and a MVC page you need to have both MVC and WebForms renderers for the block (the same goes for partial renderers for pages).
But how? …
EpiServer have made it easy for you to have different renderers, the TemplateResolver scans on init where your Block Model is used and depending of Context (webforms or MVC) it displays the right template. Yey!
What you need is a solution with both Webform Templates and MVC views. (this will be an upcoming blog post soon)
We need then one block model and two renderers, one ascx and one cshtml. Off course depending of the complexity of the partial view, you’ll may add a Controller with a ViewModel.
The Block Model: JennyBlock.cs
using EPiServer.Core; using EPiServer.DataAbstraction; using EPiServer.DataAnnotations; using System.ComponentModel.DataAnnotations; namespace Gosso.BlockTypes { [ContentType(DisplayName = "Jenny Block v1", GUID = "cdaa0690-55c8-478a-8c62-10d46f9ffc95", GroupName = "Common", Description = "Some new block that writes Jenny"), ImageUrl(path: "~/Static/Images/someimage.png")] public class JennyBlock : BlockData { [Required] [CultureSpecific] [Display(Name = "Heading", Description = "", Order = 100, GroupName = "Information")] public virtual string Heading { get; set; } } }
The CSHTML in views/shared/jennyblock.cshtml
@model Gosso.BlockTypes.JennyBlock @if (Model != null) { <div class="sendLinkContainer"> <h3>@Model.Heading Jenny MVC</h3> </div> }
The jennyblocktemplate.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="JennyBlockTemplate.ascx.cs" Inherits="Gosso.Blocks.JennyBlockTemplate" %> <div class="third sendLinkContainer"> <h3><%= CurrentBlock.Heading %> Jenny Webform</h3> </div>
And the code behind
using EPiServer.Web; using Gosso.BlockTypes; using System; namespace Gosso.Blocks { public partial class JennyBlockTemplate : BlockControlBase<JennyBlock> { protected void Page_Load(object sender, EventArgs e) { } } }
So conclusion:
- If you have a site with Webforms, and want to convert the site to MVC, this pattern helps the editor to reuse the blocks on their new MVC views.
- No need for any TemplateDescription for default templates
TIP 1. if you need different Attributes on the block models, you may just make a new one and inherit from the MVC Model.
Sources: