Search code examples
c#asp.netinline-codeparsecontrol

Workaround for ParseControl not supporting inline code blocks?


I'm using the ParseControl method in ASP.Net to render some mixed HTML and server control code which is coming from an external data source.

This is working well, however ParseControl does not seem to support inline script blocks (<% %>), and I'm wondering if there is a simple alternative or workaround for this? Here's one simple example (real world implementation is more complex):

string externalCodeString = "<div><%= DateTime.Now %></div>";
Control control = ParseControl(externalCodeString);
placeholder.Controls.Add(control);

Solution

  • ParseControl indeed does not support code blocks because it never causes any compilation.

    One approach that should work but is more complicated is to instead rely on a UserControl served by a VirtualPathProvider.

    You could then in theory wrap that into a simple API like ParseControl, but it would actually compile the user control.

    You'd have to do proper caching, to make sure you don't end up compiling on every call, which would kill perf.

    Dynamic Languages would work better for something like this :)