DD4T 1.3 comes with a few Html extension methods that allow us to render Component Presentation inside a Page Razor view using different ways of filtering through the list of ComponentPresentations on the IPage object:
There is however, no helper method that allows the rendering of just a simple plain ComponentPresentation, yet sometimes that is exactly what I would need.
Below is one such Html extension method that calls the rendering of only the given ComponentPresentation object:
Note two things about the code above:
Call this helper method using code similar to the sample below:
- RenderComponentPresentations() -- renders all ComponentPresentations on the page;
- RenderComponentPresentationsBySchema() -- renders only ComponentPresentations whose Component is based on a given Schema title or TcmUri;
- RenderComponentPresetnationsByView() -- renders only ComponentPresentations whose ComponentTemplate uses a given view name or has a given TcmUri;
There is however, no helper method that allows the rendering of just a simple plain ComponentPresentation, yet sometimes that is exactly what I would need.
Below is one such Html extension method that calls the rendering of only the given ComponentPresentation object:
public static MvcHtmlString RenderComponentPresentation(this HtmlHelper htmlHelper, IComponentPresentation cp) { if (!string.IsNullOrEmpty(cp.RenderedContent)) { return new MvcHtmlString(cp.RenderedContent); } cp.Page = PageHelper.GetPage(htmlHelper); IFieldSet metaFields = cp.ComponentTemplate.MetadataFields; string controller = metaFields.StringValue("controller"); if (string.IsNullOrEmpty(controller)) { controller = ConfigurationHelper.ComponentPresentationController; } string action = metaFields.StringValue("action"); if (string.IsNullOrEmpty(action)) { action = ConfigurationHelper.ComponentPresentationAction; } return ChildActionExtensions.Action(htmlHelper, action, controller, new { componentPresentation = (ComponentPresentation)cp }); }
Note two things about the code above:
- it uses the IFieldSetExtension methods presented in post IFieldSet Extension Methods, which allow us to read values from IFieldSet collections easily;
- it uses PageHelper.GetPage method presented in post Get the Page Model from Component Presentation, which allows us to read the Page model from the current ViewContext;
Call this helper method using code similar to the sample below:
@foreach (var cp in Model.ComponentPresentations) { <div class="content"> @Html.RenderComponentPresentation(cp) </div> }
Comments