问题
I need to set a new landing page for my application. For now it is landing on the standard Index.cshtml inside of the Home folder inside of the Views folder. I want my new landing page to be from this directory:
Views/Welcome/Index.cshtml
The error I'm getting says: InvalidOperationException: RenderBody has not been called for the page at '/Views/Welcome/Index.cshtml'. To ignore call IgnoreBody();
I have made the following changes so far in my startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.Configure<RazorViewEngineOptions>(o =>
{
o.ViewLocationFormats.Clear();
o.ViewLocationForms.Add("/Views/Welcome/Index" + RazorViewEngine.ViewExtension);
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Welcome}/{action=Index}/{id?}");
});
endpoints.MapFallbackToController("Index", "Welcome");
}
My View:
@{
ViewData["Title"] = "Index";
}
//html
//jQuery
I haven't found any resources online on how to accomplish this when using MVC.
Thanks!
回答1:
Redirect to other view
If you want to return different view
in a simply way, you could try redirecting to other view in Home/Index
.
public class HomeController : Controller
{
public IActionResult Index()
{
//return View();
return View("~/Views/Welcome/Index.cshtml");
}
}
Layout
As for the layout, _ViewStart.cshtml
(/Pages/Shared
) are run before every full view (not layouts, and not partial views).
_ViewStart.cshtml
@{
Layout = "_Layout";
}
Render JS
In the code below, you define the scripts section and render scripts inside the section.
Index.cshtml
@RenderSection("Scripts", required: true)
_ValidationScriptsPartial.cshtml
@section Scripts {
<script type="text/javascript" src="~/scripts/js1.js"></script>
<script type="text/javascript" src="~/scripts/js2.js"></script>
<script type="text/javascript" src="~/scripts/js3.js"></script>
}
回答2:
I think I have found a solution. I added Layout = null to my view (the new landing page), but it removed all of my css. I then added the paths to my css libraries inside of this file. It seems to work, but I am still open to any suggestions (if any) on how to improve any of this code. Thanks!
This is how I found my solution: Stackoverflow solution
来源:https://stackoverflow.com/questions/62662242/setting-a-new-landing-page-in-asp-net-core-mvc