grokky grokky - 17 days ago 5
ASP.NET (C#) Question

Render ASP.NET Core Razor markup from an argument

Before ASP.NET Core, I could pass Razor markup as an argument to some function. However, it doesn't seem to work anymore.

For example, even these simple cases render nothing:

@{
Func<object, HelperResult> markup1 = @<text>hello world</text>;
new HtmlString(markup1.Invoke(null).ToString());

Func<object, HelperResult> markup2 = @<h1>hello world</h1>;
new HtmlString(markup2.Invoke(null).ToString());
}


What am I doing wrong?

Answer

This wont render any result as you are not doing anything with the result.

@{
  Func<object, HelperResult> markup = @<text>hello world</text>;
  new HtmlString(markup.Invoke(null).ToString());
}

In the expression new HtmlString(markup.Invoke(null).ToString()); returns a HTML Result which is correct however the way you are calling it will not work correctly. Here is a snippet that will print the result.

@{

    Func<object, HelperResult> markup = @<text>hello world</text>;
    var html = markup.Invoke(null);
    await html.WriteAction(ViewContext.Writer);
}

You will notice here we explicitly tell the html variable (HtmlResult) where to write to. In this instance you will want to write to the ViewContext.Writer which is a System.IO.TextWriter.

Comments