Render HTML file in ASP.NET MVC view?

2019-01-11 04:09发布

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?

6条回答
Root(大扎)
2楼-- · 2019-01-11 04:18

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

@Response.WriteFile(pathToMyHtmlFile)

taken from here

查看更多
在下西门庆
3楼-- · 2019-01-11 04:28

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
查看更多
Bombasti
4楼-- · 2019-01-11 04:32

You could use this in your cshtml view:

@{this.GetOutputWriter().Write(File.ReadAllText(Server.MapPath("/your/static/file.html")));}
查看更多
聊天终结者
5楼-- · 2019-01-11 04:33

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" })
查看更多
何必那么认真
6楼-- · 2019-01-11 04:35

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.

查看更多
聊天终结者
7楼-- · 2019-01-11 04:36

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

查看更多
登录 后发表回答