Umbraco - Render .Net User Control (ascx) macro with Razor

macros, razor, render, umbraco

Solution

<umbraco:Macro runat="server" language="cshtml">@{

HtmlTextWriter writer = new HtmlTextWriter(this.Output);
var navigation = new umbraco.presentation.templateControls.Macro();

navigation.Alias = "Navigation";
navigation.MacroAttributes.Add("ulclass", "art-vmenu");
navigation.MacroAttributes.Add("level", 2);

navigation.RenderControl(writer);   }</umbraco:Macro>

Try something like this. It works for me ... I have made a Navigation macro. Be Aware though your variables should be given in toLower, if caps are used, the parameters will not come through.

Problem

I have a razor script in Umbraco that is quite complex and I want at some point of it to render a macro in it. The macro which is called SuggestionBox is actually a user control (.ascx) and traditionally this is referenced on the template using ``` <umbraco:macro Alias="SuggestionBox" language="cshtml" runat="server"></umbraco:macro> ``` But now I need to call it from the razor script instead so I tried; ``` @Html.Raw(umbraco.library.RenderMacroContent("SuggestionBox", Model.Id)) ``` as well as: ``` @RenderPage("SuggestionBox") ``` No luck so far as I'm sure I'm using these wrongly. I read somewhere it might be infeasible if the page is wrapped in a masterpage. It works if I add it to the Template like I traditionally would: ``` <umbraco:macro Alias="EventsRenderer" language="cshtml" runat="server"></umbraco:macro> <div class="talkingPointPanel"> <h3><umbraco:Item field="talkingPoinstSuggestionText" runat="server"></umbraco:Item></h3> <umbraco:macro Alias="SuggestionBox" language="cshtml" runat="server"></umbraco:macro> </div> ``` Where EventsRenderer renders the page that should ideally contain the SuggestionBox. using ``` @Html.Raw(umbraco.library.RenderMacroContent("<?UMBRACO_MACRO macroAlias=\"SuggestionBox\" />", Model.Id)) ``` Gives me this error: ``` <!-- Error generating macroContent: 'System.Web.HttpException (0x80004005): HtmlForm cannot render without a reference to the Page instance. Make sure your form has been added to the control tree. at System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) at umbraco.presentation.templateControls.Macro.Render(HtmlTextWriter writer) at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) at umbraco.library.RenderMacroContent(String Text, Int32 PageId)' --> ``` Any ideas?

Original source