0

I am working on an ASP.NET MVC web application.

On one page, I have a string that looks as follows:

<p>
    <i>This</i> is some <strong>text</strong>&nbsp;!
</p>

For preview mode, I use Html.Raw(Model.MyText), and the text is displayed as rendered HTML:

This is some text !

I want to now add a button to allow users to view the actual source of this text. I would like the button to open a new tab that displays the HTML text, formatted in a way that is readable, with proper line breaks and indentation.

Idea 1:

Based off the ideas I found here, my first though was to try to open the view-source mode of a URL, with a link similar to the following:

<a target="_blank" href="view-source:http://www.example.com/">View source</a>

This would render the text exactly how I would like it to render:

view-source

However, as of this Bugzilla fix, access to view-source URLs is denied.

Idea 2:

My next attempt was to get the innerHTML, and write that text to a new window:

function showSource(){
    source += document.getElementById('myDivID').innerHTML;
    source = source.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    source = "<pre>" + source + "</pre>";
    sourceWindow = window.open('', '_blank');
    sourceWindow.document.write(source);
    sourceWindow.document.close();
    if(window.focus) sourceWindow.focus();
}

The method successfully passes the text over to a new tab, however, the code is displayed in a single, unformatted line that is not readable:

<p><i>This</i> is some <strong>text</strong>&nbsp;!</p>

Idea 3:

I also thought of just removing the Html.Raw(), however this idea also renders the code in an unreadable format:

<p><i>This</i> is some <strong>text</strong>&nbsp;!</p>

How can I get Model.MyText string to open in a new tab and render as prettified HTML?

Ideally, it would be great if this can be accomplished with just HTML or JavaScript, but I'm open to ideas that would require a call to an MVC ActionResult as well.

Community
  • 1
  • 1
Tot Zam
  • 8,406
  • 10
  • 51
  • 76

0 Answers0