Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering .html files as views in ASP.NET MVC

Tags:

asp.net-mvc

I would like to have .html files serve as views alongside other .cshtml views in my ASP.NET MVC project. The main reason for this is so that the html files are subject to the same custom security rules in my actions that the other views abide by.

I don't want to use the .cshtml or .aspx extensions because then the framework attempts to compile these rather large files which is waste since the files don't have anything to compile.

I've updated the view engine to look for .html extensions. This works fine, but then the error I'm getting is that I don't have a registered build provider. I've tried registering a build provider for .html files in the web.config, but that doesn't make any difference in the error.

Is there a build provider that will just pass the text from the .html file straight through without attempting to compile it?

So what I'm looking for is for .html files to live in the views directory so they are only rendered when requested through an action, and the .html views shouldn't be run through any compilation.

Thanks,

Chris

like image 583
Chris Sutton Avatar asked Jul 27 '11 18:07

Chris Sutton


People also ask

What method is used to render HTML string in a view?

You can use the Html. Raw() method for that.

How open HTML file in MVC?

In this example, I will show you how to load an html page in asp.net MVC view. You can call an html page from your view using Html. Action helper method. In controller action you can return an HTML file by using FilePathResult; it will return the content of the file to the response.

What is rendered in view of MVC?

A view renders the appropriate UI by using the data that is passed to it from the controller. This data is passed to a view from a controller action method by using the View method. The Views folder is the recommended location for views in the MVC Web project structure.


2 Answers

I found a solution. In my action I return FilePathResult and it just loads the file and passes it through without any compilation.

return new FilePathResult("path_and_file.html", "text/html");
like image 117
Chris Sutton Avatar answered Oct 20 '22 00:10

Chris Sutton


If you want to do it for one of your action method @Chris/ @Marius are awesome. as they given:

return new FilePathResult("path_and_file.html", "text/html");
//or better use
return File("path_and_file.html", "text/html");

I would like to add one more solution to the problem if you want to do it in web config to return pure html views from Views Folder:

<!-- web.config under the Views folder -->

<system.webserver>
<handlers>

<add name="HtmlScriptHandler" path="*.html" verb="*" precondition="integratedMode"
     type="System.Web.StaticFileHandler" />
</handlers>
</system.webserver>

Here is a post suggesting it.

like image 3
Shri Avatar answered Oct 20 '22 01:10

Shri