Templated Razor Delegates combined with Partial Views

I was with a customer in Germany this week, and just before I left one of the (rather talented I might say) developers asked me about passing markup into an HtmlHelper extension. It turns out this is pretty easy, as covered by Phil Haack under Templated Razor Delegates. However, I particularly like keeping my HTML markup in cshtml files. It’s just easier to maintain. So I combined Phil’s post with the use of a partial view. The nice simple HtmlHelper extension looks like this;

 1: public static MvcHtmlString Region<TModel>( 
 2:    this HtmlHelper<TModel> html, 
 3:    Func<TModel, object> content) 
 4: { 
 5:    var result = content(html.ViewData.Model); 
 6:    return html.Partial("_Region", result); 
 7: } 

This accepts a Func<TModel, object> which is the Templated Razor Delegate. This is quite simply a snippet of Razor syntax that is executed to return markup as “result”.

 1: @Html.Region(@<text>@Model.WelcomeMessage</text>)

I’ve combined my HtmlHelper extension with a partial view named _Region, stored in the Shared folder;

 1: <fieldset class="demoregion"> 
 2:     <legend>A Region</legend> 
 3:     <div> 
 4:         @Model 
 5:     </div> 
 6: </fieldset>

This would be way neater if I could use an @helper under App_Code, but in MVC 3 that feature doesn’t support using HtmlHelper, so you couldn’t use Html.Textbox in the template, for example.

The code is attached – easy huh?

Comments (0)

Skip to main content