找不到适合类型 'System.Collections.Generic.IEnumerable`1[TeamCloud.Areas.Identity.Data.TeamCloudUser]' 的构造函数

A suitable constructor for type 'System.Collections.Generic.IEnumerable`1[TeamCloud.Areas.Identity.Data.TeamCloudUser]' could not be located

我正在使用 IdentityFramework 开发我的 ASP NET Core 项目,现在我需要在我的 RazorPage 上 table 中的参数中显示用户列表。另外,我无法想象如何将对象从 razor OnGet 方法移动到视图(我需要移动成员对象并将其显示在视图中)。无论如何,我只需要显示具有与登录用户相似的团队的用户(请参见下面的代码),但我遇到了这个错误。希望你能帮助我。谢谢。

错误

MembersList.cshtml

@page
@using TeamCloud.Areas.Identity.Pages.Team.Manage
@model IEnumerable<TeamCloudUser>
@{
   ViewData["Title"] = "Список участников";
   ViewData["ActivePage"] = ManageNavPages.MembersList;
 }
 <br />
 <div style="text-align: center;">
     <h2 style="font-weight: 700;">Настройки команды</h2>
 </div>
 <hr />
 <partial name="_ManageNav" />
 <hr />

 <body class="index">
<form method="post" asp-page="MembersList">
    <h4 style="font-weight: 700; text-align: center;">@ViewData["Title"]</h4>
    <div class="text-center">
        <input type="submit" asp-page-handler="AddMember" class="btn alert-primary" value="Добавить участника" style="cursor: pointer; font-weight: 700;" />
        <br />
        <table class="table" style="text-align: center">
            <tr>
                <th>
                    <a>Имя</a>
                </th>
                <th>
                    <a>Почта</a>
                </th>
                <th>
                    <a>Кол-во файлов</a>
                </th>
                <th>
                    <a>Объем памяти</a>
                </th>
                <th>
                    <a>Действия</a>
                </th>
            </tr>
            @foreach (var member in Model.TeamCloudUsers)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => member.ProfileName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.Email)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.TotalFiles)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.TotalSize)
                    </td>
                    <td>
                        @if (@member.IsBlockedToUpload == true)
                        {
                            <a href="" data-toggle="modal" data-target="#modalOnAllow" class="">
                                <img style="width: 30px;" src="~/Media/MenuIcons/allow.png" title="Заблокировать" />
                            </a>
                        }
                        else
                        {
                            <a href="" data-toggle="modal" data-target="#modalOnBlock" class="">
                                <img style="width: 30px;" src="~/Media/MenuIcons/block.png" title="Заблокировать" />
                            </a>
                        }
                        <a href="" data-toggle="modal" data-target="#modalOnDelete" class="">
                            <img style="width: 30px;" src="~/Media/MenuIcons/delete.png" title="Выгнать" />
                        </a>

                        <!--modalOnBlock-->
                        <div class="modal fade" id="modalOnBlock" tabindex="-1" role="dialog" aria-labelledby="title" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="title">Блокировка пользователя</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        Запретить участнику "@member.Email" загружать новые файлы в командное хранилище?.
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" asp-page-handler="BlockToUpload" class="btn alert-primary" value="@member.Id" name="userId">Запретить</button>
                                        <button type="button" class="btn alert-primary" data-dismiss="modal">Отмена</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!--modalOnAllow-->
                        <div class="modal fade" id="modalOnAllow" tabindex="-1" role="dialog" aria-labelledby="title" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="title">Разблокировка пользователя</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        Предоставить пользователю "@member.Email" доступ к загрузке файлов в хранилище команды?
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" asp-page-handler="AllowToUpload" class="btn alert-primary" value="@member.Id" name="userId">Разрешить</button>
                                        <button type="button" class="btn alert-primary" data-dismiss="modal">Отмена</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!--modalOnDelete-->
                        <div class="modal fade" id="modalOnDelete" tabindex="-1" role="dialog" aria-labelledby="title" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="title">Исключение пользователя</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        Исключить пользователя "@member.Email" из команды? (тут подумать над удалением его файлов)
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" asp-page-handler="DeleteFromTeam" class="btn alert-primary" value="@member.Id" name="userId">Исключить</button>
                                        <button type="button" class="btn alert-primary" data-dismiss="modal">Отмена</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
            }
        </table>
    </div>
</form>

MembersList.cshtml.cs

namespace TeamCloud.Areas.Identity.Pages.Team.Manage
{
 public class MembersListModel : PageModel
 {

    private readonly IWebHostEnvironment webHostEnvironment;
    private readonly UserManager<TeamCloudUser> _userManager;
    private readonly ILogger<TeamCloudUser> _logger;
    private readonly TeamCloudContext _context;

    SqlConnection sqlConnection = new SqlConnection("Data Source=DESKTOP-LRLFA5K\SQLEXPRESS;Initial Catalog=TeamCloud;Integrated Security=True");

    private string currentUserId { get; set; }

    public MembersListModel(IWebHostEnvironment webHostEnvironment, UserManager<TeamCloudUser> userManager, ILogger<TeamCloudUser> logger, TeamCloudContext context)
    {
        this.webHostEnvironment = webHostEnvironment;
        _userManager = userManager;
        _logger = logger;
        _context = context;
    }

    public IActionResult OnGetAsync()
    {
        var teamFounder = _userManager.GetUserId(User);
        currentUserId = teamFounder;
        int currentTeamId = FindTeamIdByName();
        var teamMembers = _context.AspNetUserTeams.Where(x => x.TeamId == currentTeamId).Select(x => x.UserId);
        string partialValue = null;
        var members = partialValue;
        foreach (var member in teamMembers)
        {
            members += _context.Users.Where(x => x.Id == member).FirstOrDefault();
        }
        return ??? //How to move object modal members to view in RazorPages?
    }

    public IActionResult OnPostAddMember()
    {
        return RedirectToPage("AddMember");
    }

    private int FindTeamIdByName()
    {
        sqlConnection.Open();
        SqlCommand sqlCommand = new SqlCommand("select TeamId from AspNetUserTeams where UserId = @userId", sqlConnection);
        sqlCommand.Parameters.Add("@userId", SqlDbType.NVarChar);
        sqlCommand.Parameters["@userId"].Value = currentUserId;
        DataSet dataSet = new DataSet();
        var dataAdapter = new SqlDataAdapter { SelectCommand = sqlCommand };
        dataAdapter.Fill(dataSet);
        sqlConnection.Close();
        return Convert.ToInt32(dataSet.Tables[0].Rows[0]["TeamId"]);
    }
}

}

TeamCloudUser

namespace TeamCloud.Areas.Identity.Data
{
    // Add profile data for application users by adding properties to the TeamCloudUser class
    public class TeamCloudUser : IdentityUser
{
    //public virtual new string Email { get; set; }
    public string ProfileName { get; set; }

    public bool IsBlockedToUpload { get; set; }

    public int TotalFiles { get; set; }
    public string TotalSize { get; set; }
}

}

您首先需要了解如何开始使用 razor 页面:

https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-5.0&tabs=visual-studio#razor-pages

Razor Pages 不使用 @model ModelName,它使用 @model <PageName>Model,这与 mvc 不同。

根据您的要求,您不知道如何 return 在剃须刀 pages.Change 中建模,如下所示:

MembersList.cshtml:

@page
@model MembersListModel    //change here
<body class="index">
    <form method="post" asp-page="MembersList">
        <h4 style="font-weight: 700; text-align: center;">@ViewData["Title"]</h4>
        <div class="text-center">
            <input type="submit" asp-page-handler="AddMember" class="btn alert-primary" value="Добавить участника" style="cursor: pointer; font-weight: 700;" />
            <br />
            <table class="table" style="text-align: center">
                <tr>
                    <th>
                        <a>Имя</a>
                    </th>
                    //....
                </tr>
                @foreach (var member in Model.TeamCloudUsers)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => member.ProfileName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.Email)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.TotalFiles)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => member.TotalSize)
                    </td>
                    <td>
                        @if (@member.IsBlockedToUpload == true)
                        {
                            <a href="" data-toggle="modal" data-target="#modalOnAllow" class="">
                                <img style="width: 30px;" src="~/Media/MenuIcons/allow.png" title="Заблокировать" />
                            </a>
                        }
                        else
                        {
                            <a href="" data-toggle="modal" data-target="#modalOnBlock" class="">
                                <img style="width: 30px;" src="~/Media/MenuIcons/block.png" title="Заблокировать" />
                            </a>
                        }
                        <a href="" data-toggle="modal" data-target="#modalOnDelete" class="">
                            <img style="width: 30px;" src="~/Media/MenuIcons/delete.png" title="Выгнать" />
                        </a>

                        <!--modalOnBlock-->
                        <div class="modal fade" id="modalOnBlock" tabindex="-1" role="dialog" aria-labelledby="title" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="title">Блокировка пользователя</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        Запретить участнику "@member.Email" загружать новые файлы в командное хранилище?.
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" asp-page-handler="BlockToUpload" class="btn alert-primary" value="@member.Id" name="userId">Запретить</button>
                                        <button type="button" class="btn alert-primary" data-dismiss="modal">Отмена</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!--modalOnAllow-->
                        <div class="modal fade" id="modalOnAllow" tabindex="-1" role="dialog" aria-labelledby="title" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="title">Разблокировка пользователя</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        Предоставить пользователю "@member.Email" доступ к загрузке файлов в хранилище команды?
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" asp-page-handler="AllowToUpload" class="btn alert-primary" value="@member.Id" name="userId">Разрешить</button>
                                        <button type="button" class="btn alert-primary" data-dismiss="modal">Отмена</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!--modalOnDelete-->
                        <div class="modal fade" id="modalOnDelete" tabindex="-1" role="dialog" aria-labelledby="title" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="title">Исключение пользователя</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        Исключить пользователя "@member.Email" из команды? (тут подумать над удалением его файлов)
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" asp-page-handler="DeleteFromTeam" class="btn alert-primary" value="@member.Id" name="userId">Исключить</button>
                                        <button type="button" class="btn alert-primary" data-dismiss="modal">Отмена</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
            }
            </table>
        </div>
    </form>
</body>

MembersList.cshtml.cs:

public class MembersListModel : PageModel
{
    //1. add the following property
    public IEnumerable<TeamCloudUser> TeamCloudUsers { get; set; }
    
    public void OnGet()
    {
        //2. set data for the property
        //for easy testing,I hard-coded the data
        //you could get the data from database
        //e.g. TeamCloudUsers = _context.AspNetUserTeams
        //                              .Where(x => x.TeamId == currentTeamId).ToList();
        TeamCloudUsers = new List<TeamCloudUser>()
        {
            new TeamCloudUser(){ ProfileName ="a",IsBlockedToUpload=false,Email="a@qq.com",TotalFiles=2,TotalSize="34"}
        };
    }
}

结果:

更新:

将您的代码修改为:

                                         // change here...
<a href="" data-toggle="modal" data-target="#modalOnBlock_@member.Id" class="">
                                <img style="width: 30px;" src="~/Media/MenuIcons/block.png" title="Заблокировать" />
</a>
<!--modalOnBlock-->
                                 //change here...
<div class="modal fade" id="modalOnBlock_@member.Id" tabindex="-1" role="dialog" aria-labelledby="title" aria-hidden="true">