我有AccountController.cs,并有以下操作:
[HttpGet]
[AllowAnonymous]
public IActionResult Register()
{
ViewBag.Registration = GetRegistration();
return View();
}
ViewBag.Registration包含2个元素,没关系。
然后我得到了Registration.cshtml视图:
@model Registration <!-- this model I'm using for other form -->
@{
Layout = "_Layout";
}
<!-- some code -->
@await Html.PartialAsync("AllRegistered")
和AllRegistered.cshtml,其中应显示ViewBag.Registration中的数据:
@model IEnumerable<Registration>
<table>
<tr>
<th>@Html.DisplayNameFor(m => m.Email)</th>
<th>@Html.DisplayNameFor(m => m.City)</th>
</tr>
@if (Model != null && Model.Count() != 0)
{
@foreach (Registration registration in Model)
{
<tr>
<th>@Html.DisplayFor(m => registration.Email)</th>
<th>@Html.DisplayFor(m => registration.City)</th>
</tr>
}
}
</table>
但是什么都没有生成,我认为模型是空的。
PartialAsync方法包含一个包含模型的重载:
Html.PartialAsync(string partialViewName, TModel model)
您应该在该帮助器中包括IEnumerable<Registration>
(局部视图的模型)。
如果GetRegistrations()返回该IEnumerable,则应这样定义部分视图:
@await Html.PartialAsync("AllRegistered", (List<Registration>)ViewBag.Registration)
虽然Nathan的答案是完全正确的,但将其作为视图组件会更合适。您想要显示所有注册的事实是与该操作的目的无关的视图详细信息。因此,要让该操作负责检索数据,就需要该操作具有不需要和不应该拥有的知识。
相反,添加一个类,如:
public class AllRegistrationsViewComponent : ViewComponent
{
private readonly RegistrationsService _service;
public AllRegistrationsViewComponent(RegistrationService service)
{
_service = service;
}
public async Task<IViewComponentResult> InvokeAsync()
{
// logic behind `GetRegistrations()` here
return View(registrations);
}
}
这里对RegistrationsService
的引用就是您用来检索注册的任何方式,以显示如何将其注入到组件中。这可能是您的情况或完全是其他情况。
然后,使用以下命令创建视图Views/Components/AllRegistrations/Default.cshtml
:>
@model IEnumerable<Registration> <table> <tr> <th>@Html.DisplayNameFor(m => m.Email)</th> <th>@Html.DisplayNameFor(m => m.City)</th> </tr> @if (Model != null && Model.Count() != 0) { @foreach (Registration registration in Model) { <tr> <th>@Html.DisplayFor(m => registration.Email)</th> <th>@Html.DisplayFor(m => registration.City)</th> </tr> } } </table>
路径的
AllRegistrations
部分基于视图组件的名称,而没有ViewComponent
部分,因此,如果您使用不同的名称,也请在此处进行调整。
最后,在您看来:
@await Component.InvokeAsync("AllRegistrations")
然后,您的操作可以只关注其实际目的:
[HttpGet]
[AllowAnonymous]
public IActionResult Register()
{
return View();
}