我想从ASP.NET MVC Core的Layout.cshtml页面中的数据库加载,但是我不能在mvc内核中使用Child Action!
请帮助我!
答案 0 :(得分:0)
您需要编写控制器来像这样从db获取数据
public ActionResult GetFooterCategories()
{
var categories = db.Categories.ToList();
return PartialView("FooterCategory",Categories);
}
然后在您的layout.cshtml中添加
@Html.RenderAction("GetFooterCategories","Home")
希望有帮助。
答案 1 :(得分:0)
您可以通过HttpContextAccessor
获取dbContext。请参阅下面的演示。
1。在startup.cs中注册:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
2._Layout.cshtml:
<footer class="border-top footer text-muted">
@using Microsoft.AspNetCore.Http
@using YourDbContextNameSpace
@using Microsoft.Extensions.DependencyInjection
@inject IHttpContextAccessor HttpContextAccessor
@{
var context = HttpContextAccessor?.HttpContext?.RequestServices?.GetRequiredService<YourDbContext>();
var data = context.Products.ToList();//an example to get data from db
}
@foreach(var d in data)
{
<span>@d.Name</span>
}
<div class="container">
© 2019 - xxx - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>