Home > front end >  Static Files in Header
Static Files in Header

Time:01-27

I am trying to include static files resides outside of the wwwroot folder to _Layout.chtml. How to make this happen? For example, I have header.html and footer.html under include folder which is located under the project folder, I create a _Layout.chtml and want to add the header and footer files as partial views? Below is the Program.cs code:

using Microsoft.Extensions.FileProviders; //access files outside webroot
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(@"C:\MyProjects\myprograms\WebApplication1\include"),
    RequestPath = new PathString("/include")
});


app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

My _Layout.cshtml file

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
   @Html.Partial("/include/header")
</head>
<body>
    <div>
        @RenderBody()
    </div>
    @Html.Partial("/include/footer")
</body>
</html>

When I start the application, I receive the error message as below: InvalidOperationException: The partial view '/include/header' was not found. The following locations were searched: /include/header Please advice! Thanks.

CodePudding user response:

The Html.Partial method is used render the MVC view not the html static file, I don't suggest you use it to render the html. This has no difference between render a MVC partial view and the static html file.

If you want to include some html file inside your layout, I suggest you could consider using Jquery to achieve your requirement.

Like this answer said:

<html> 
  <head> 
    <script src="jquery.js"></script> 
    <script> 
    $(function(){
      $("#includedContent").load("b.html"); 
    });
    </script> 
  </head> 

  <body> 
     <div id="includedContent"></div>
  </body> 
</html>

B is another html.

  • Related