2

I have a custom field in Sitecore - a composite field with a number and a rich text editor.

The editor side of things works great, but when the field is rendered without the page editor, I'd like to delegate the formatting of it to a cshtml file - sending an object of my choosing in as the model.

I can intercept the rendering in DoRender:

    protected override void DoRender(HtmlTextWriter output)
    {
        if (!Sitecore.Context.PageMode.IsPageEditor)
        {
            //here is where I want to delegate the output to a cshtml DisplayTemplate with the Value as the Model.
        }
        else
        {
            base.DoRender(output);
        }
    }

But how do I delegate the output to a cshtml DisplayTemplate with the Value as the Model?

TheSoftwareJedi
  • 34,421
  • 21
  • 109
  • 151

1 Answers1

2

You would have to render the view to a string, then you can use that with the HtmlTextWriter to render out.

This would render a view to a string:

public static string RenderPartialToString(string controlName, object viewData)
{
    ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };

    viewPage.ViewData = new ViewDataDictionary(viewData);
    viewPage.Controls.Add(viewPage.LoadControl(controlName));

    StringBuilder sb = new StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    {
        using (HtmlTextWriter tw = new HtmlTextWriter(sw))
        {
            viewPage.RenderControl(tw);
        }
    }
    return sb.ToString();
}

Then you can modify your code like this:

protected override void DoRender(HtmlTextWriter output)
{
    if (!Sitecore.Context.PageMode.IsPageEditor)
    {
        //here is where I want to delegate the output to a cshtml DisplayTemplate with the Value as the Model.
        var model = new {}; // create your model
        var viewString = RenderPartialToString("~/path/to/view.cshtml", model);
        output.Write(viewString);
    }
    else
    {
        base.DoRender(output);
    }
}

Note that this method would bypass Sitecore rendering pipelines when rendering the .cshtml file.

Credit for the RenderPartialToString method - How to Render Partial View into a String

Community
  • 1
  • 1
Richard Seal
  • 4,248
  • 14
  • 29