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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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" })
Method 2
I think it’s a better solution:
Use WriteFile from the Response object
@Response.WriteFile(pathToMyHtmlFile)
taken from here
Method 3
Follow these steps
- Create a view in
~/views/sharedfolder. give it nametest.cshtml. - Copy the content of HTML in it.
- Use
Html.Partial("test")on page to render the html of that view.
Method 4
The simple answer is to rename the main.html file to main.cshtml which will be recognized by the Razor view engine for rendering.
Method 5
You could use this in your cshtml view:
@{this.GetOutputWriter().Write(File.ReadAllText(Server.MapPath("/your/static/file.html")));}
Method 6
A total different way is just load the file in javascript
<div id="loadId">
</div>
<script>
$(document).ready(function () {
$('#loadId').load('filepath');
});
</script>
You can set the filepath in the controller, or put it in the model, if you want, and use:
$('#loadId').load('@ViewBag.filepath');
Method 7
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0