问题
I am making an ASP.NET Core MVC project. I have a HomeController set up, I have the Views folder with the Home and Shared folders set up, and inside those I have the appropriate .cshtml files (such as Index.cshtml, _Layout.cshtml, and _ViewStart.cshtml). I also have a PartialViews folder which has a bunch of HTML files (not .cshtml files).
All I want to do is make an Ajax get request from the browser for an HTML file in the PartialViews folder (which, just to be clear, has the path MyProject\Areas\MyArea\PartialViews\SomeDoc.html). I know that if this HTML file were in the wwwroot folder (where static files are kept -- I am also using this) I could just make a get request to the url 'localhost/SomeDoc.html'. But it's not under wwwroot, so I guess I have to go through the HomeController I defined in MyArea? I'm not sure how to format the get request so that return View()
in HomeController.Index()
knows to fetch and return the html file in the specified folder path. I've tried this url: 'localhost/MyArea/Home/PartialViews/SomeDoc.html', though that just returns a 404.
ASP.NET Core docs pertaining to MVC don't really seem to address this unless I'm misunderstanding them. Another thing I'm not sure about is whether these HTML files in this PartialViews folder are supposed to be used like this article on using partial views with MVC describes. I'm confused because the article (a) only references .cshtml files (whereas I just have html files), and (b) doesn't explain how to format the request for the view (unless, again, I'm missing something).
回答1:
It seems you need to spend some more time with docs. The only publicly served directory by default is wwwroot
. If you want another directory to be served as well by the static files middleware, you need to configure that. However, it would be totally 100% inappropriate to serve your Views
directory directly, so don't do that.
If you want to be able to request static HTML files, add them under wwwroot
or create a totally different directory just for that purpose and serve that as well via the static files middleware.
Typically, though, static HTML isn't overly useful, and if you truly need static HTML, it begs the question of why it's just not part of the view to begin with. The normal path is to have .cshtml
views, which ASP.NET Core will render to HTML as part of the request pipeline to return the response.
Simply, you just create an action that returns PartialView
and pass in the name of the .cshtml
file you want to return, along with a model, if applicable. In your JS, then, you do an AJAX request to the route bound to that action, and you get back your partial view rendered into HTML.
来源:https://stackoverflow.com/questions/49524917/how-to-make-a-get-request-for-an-html-file-using-asp-net-core-mvc