0

I'm looking for a way to write a value in my razor view, without encoding it, AND without using the Html Helper.

I'm rendering the view in a hybrid website, where I parse my View programmatically, like this:

 string html = "<html>@("Write something <strong>unencoded</strong>"</html>")
 html = Razor.Parse<TModel>(html, model);

So essentially, my html variable contains a template containing razor c# code. Because I am compiling my view like this, I have no access to the Html helper (the accepted answer in this post implies this is indeed the case: How to render a Razor View to a string in ASP.NET MVC 3?)

However, my html variable also contains a statement like this:

 @Html.Raw("<strong>This should be printed unencoded</strong>")

This does not work but gives "Html is not available in this context".

How can I achieve the same behavior? Using Response.Write gives the exact same error.

Are there any other ways?

Note: this is a hybrid website, containing both classic ASP webforms and some newer Web API and MVC stuff. The View I'm using is NOT accessed through conventional MVC ways.

Community
  • 1
  • 1
Steven Lemmens
  • 620
  • 5
  • 18

2 Answers2

1

HtmlString type of string should work for you.

Represents an HTML-encoded string that should not be encoded again.

Sample with creating such string inline (normally you'd have such values in Model set by controler):

  @(new HtmlString("<strong>This should be printed unencoded</strong>"))
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • Reading that documentation, I assume you're right. However, printing this doesn't work: @(new HtmlString("this should be unencoded")) and produces the HTML literally (meaning it was encoded) – Steven Lemmens Jun 01 '15 at 22:38
  • I found a way around this. I updated my question. It's not perfect, but it seems to work. – Steven Lemmens Jun 02 '15 at 08:08
1

It took me a while to figure out, but this is the final solution (which works for me, but has some security implications, so do read on!)

Compile your view like this

var config = new TemplateServiceConfiguration();
config.EncodedStringFactory = new RawStringFactory();

var service = RazorEngineService.Create(config);
html = service.RunCompile(html, "templateNameInTheCache", null, model);

As you can see, I employed the RawStringFactory to make sure no HTML at all gets encoded. Of course, MVC automatically encodes HTML as a safety precaution, so doing this isn't very safe. Only do this if you're 100% sure that all of the output in the entire Razor view is safe!

Steven Lemmens
  • 620
  • 5
  • 18