Render HTML file in ASP.NET MVC view?

2019-01-11 03:45发布

问题:

In my view, would like to render the contents of an HTML file as a partial view. It is giving me this error though when I add this to the .cshtml view:

@Html.Partial(Url.Content("~/Test/main.html"))

Errors:

Exception Details: System.InvalidOperationException: The partial view '/Scripts/main.html' was not found or no view engine supports the searched locations. The following locations were searched:
/Scripts/main.html

The file is physically there though. Is there a different way I should be doing this?

回答1:

You can't use Html.Partial for this.It is a special helper method for rendering Partial Views. Instead you can add an Action like this:

[ChildActionOnly]
public ActionResult GetHtmlPage(string path)
{
   return new FilePathResult(path, "text/html");
}

And you can call it from your View with using Html.Action helper Method:

@Html.Action("GetHtmlPage","controllername", new { path = "~/Test/main.html" })


回答2:

The simple answer is to rename the main.html file to main.cshtml which will be recognized by the Razor view engine for rendering.



回答3:

Follow these steps

  1. Create a view in ~/views/shared folder. give it name test.cshtml
  2. Copy the content of html in it.
  3. Use html.partial("test") on page to render the html of that view


回答4:

I think it's a better solution: Use WriteFile from the Response object

@Response.WriteFile(pathToMyHtmlFile)

taken from here



回答5:

You could use this in your cshtml view:

@{this.GetOutputWriter().Write(File.ReadAllText(Server.MapPath("/your/static/file.html")));}


回答6:

Just use an ajax request to fetch the html file output the content into your main html. Since it is an html file, it will be cached in subsequent calls and there will be no performance impact.