Saturday, January 16, 2010

Displaying External HTML file content in Microsoft MVC


We are developing an application where one of our MVC views is simply to render HTML snippets from an external file.  Since our favorite internet search engine did not turn up any information on how to do this, I am posting the following information. 

In our case the external HTML is a fairly simple snippet without javascript or form tags, so no manipulation of the file contents is required before display.

You can quickly read in the entire file to a string as follows:

using System.IO;

public static string GetHTMLContents(string filename)
string results = string.Empty;
if (File.Exists(filename))
results = File.ReadAllText(filename);
return results;

Then just place that string in the ViewData with a command like

ViewData["HTMLContent"] =  results;

and in the View render it with code that looks like:

<span style=" text-decoration:underline">HTML Content:</span><br/>
<%= ViewData["HTMLContent"] %>

Hope that helps.

Joe Kunk

Microsoft MVP

Okemos, MI USA

January 16, 2010


This comment has been removed by a blog administrator.
Vijay Jagdale said...

That's a nice tip.

If all you need to show is HTML content, here are some other cool ways to do it (no need to create a view):

public ActionResult myhtml1(){
return Content(System.IO.File.ReadAllText(@"C:\stuff.htm"));

an even simpler way:

public void myhtml2(){

Here is a cool way to grab content from some other website and pipe it to a response:

public void myhtml3(){
var wreq = System.Net.WebRequest.Create("");
var wresp = wreq.GetResponse();
var sr = new System.IO.StreamReader(wresp.GetResponseStream());