据我所知,Partial页面只有cshtml代码,而ViewComponent只有cs代码。 也许我的方法是错误的,但我试图在另一个页面中渲染一个完整的页面(cshtml + cshtml.cs)。
真实的例子。 Visual Studio 2017,ASP.NET Core 2。
NavBar.cshtml:
@page
@model MyProject.NavBarModel
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link" asp-page="/Machines">@Resources.Machines</a></li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">@Resources.Orders</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" asp-page="/RunningOrders">@Resources.Running <span class="badge badge-primary">@ViewData["running"]</span></a>
<a class="dropdown-item" asp-page="/OpenOrders">@Resources.Opened <span class="badge badge-primary">@ViewData["running"]</span></a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" asp-page="/SuspendedOrders">@Resources.Suspended <span class="badge badge-danger">@ViewData["running"]</span></a>
</div>
</li>
<li class="nav-item"><a class="nav-link" asp-page="/Tables">@Resources.Lists</a></li>
<li class="nav-item"><a class="nav-link" asp-page="/About">@Resources.About</a></li>
</ul>
</div>
NavBar.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using MyProject.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyProject
{
public class NavBarModel : PageModel
{
private readonly MyContext _context;
public NavBarModel(MyContext context)
{
_context = context;
}
public List<Order> Orders { get; set; }
public async Task OnGetAsync()
{
Orders = await _context.Orders.ToListAsync();
ViewData["open"] = _context.Orders.Where(x => x.State == OrderStates.Open).Count();
ViewData["running"] = _context.Orders.Where(x => x.State == OrderStates.Running).Count();
ViewData["suspened"] = _context.Orders.Where(x => x.State == OrderStates.Suspended).Count();
}
}
}
_Layout.cshtml:
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top mb-2">
<a asp-page="/Index" class="navbar-brand">Production Assistant</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
@Html.Partial("NavBar", new NavBarModel())
</nav>
<div class="container body-content">
@RenderBody()
</div>
</body>
在此示例中,我尝试在Navbar中添加徽章。因为_Layout文件后面没有代码,所以我必须把它放在一个单独的页面(NavBar)中。
问题在于,当我尝试渲染页面时,它会询问构造函数参数。我害怕我以这种方式破坏了依赖注入。