将模型传递到PartialAsync视图(Razor,MVC)

问题描述 投票:0回答:2

我有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>

但是什么都没有生成,我认为模型是空的。

asp.net-mvc asp.net-core model-view-controller razor viewbag
2个回答
1
投票

PartialAsync方法包含一个包含模型的重载:

Html.PartialAsync(string partialViewName, TModel model)

您应该在该帮助器中包括IEnumerable<Registration>(局部视图的模型)。

如果GetRegistrations()返回该IEnumerable,则应这样定义部分视图:

@await Html.PartialAsync("AllRegistered", (List<Registration>)ViewBag.Registration)


0
投票

虽然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();
}
© www.soinside.com 2019 - 2024. All rights reserved.