将模型传递到部分异步视图(Razor、MVC)



我有帐户控制器.cs,操作如下:

[HttpGet]
[AllowAnonymous]
public IActionResult Register()
{
ViewBag.Registration = GetRegistration();
return View();
}

ViewBag.Registration包含 2 个元素,没关系。

然后我得到了注册.cshtml视图:

@model Registration <!-- this model I'm using for other form -->   
@{
Layout = "_Layout";
}    
<!-- some code -->
@await Html.PartialAsync("AllRegistered")

AllRegister.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();
}

最新更新