Is there a way to render a webpart through the API?

Marcel Guldemond asked on October 24, 2016 16:28

The setup:

  • Our site is running the as the CMS portal app (for use by the client's content editors), with some sections running in an MVC app (so we can leverage the previous version of the app and its product data, which was built in ASP.NET MVC), within the same solution.
  • The main navigation & menu options on the site header are generated by a Hierarchical Viewer in the CMS master template.

The Problem:

  • We need the MVC pages to display the same nav & menu.

The Questions:

  • Is there a way using the API to get the nav webpart from the master template, and then render it to html so it can be inserted into the headers on the MVC pages?
  • Or should we be using .NET System.Web / UserControl to get and render the Nav?

Like this?

PageTemplateInfo masterTemplateInfo = PageTemplateInfoProvider.GetPageTemplateInfo("MasterTemplate");
WebPartZoneInstance menuZone = masterTemplateInfo.WebPartZones.Find(x => (string)x.GetValue("Name") == "Menu");
WebPartInstance menuWebPart = menuZone.GetWebPart("mainmenu", false);
//do the rendering here?

Or like this?

 UserControl uc = new UserControl();
            CMSWebParts_Viewers_Documents_cmsuniview newMenuControl =
            StringBuilder myStringBuilder = new StringBuilder();
            TextWriter myTextWriter = new StringWriter( myStringBuilder );
            HtmlTextWriter myWriter = new HtmlTextWriter( myTextWriter );
            newMenuControl.RenderControl( myWriter );
            string htmlOut = myTextWriter.ToString();

   Please, sign in to be able to submit a new answer.