ASP.NET 核心 MVC - 数据不会在 post 请求中从视图传递到控制器

ASP.NET Core MVC - Data does not pass from the view to the controller in a post request

我试着关注这个类似的问题: 一切在结构上几乎都是相似的,但是来自视图的数据仍然无法到达控制器。

这是视图模型:

public class ManageUsersViewModel
{
       public Guid? ProjectId;
       public List<ProjectUserRowModel> ProjectUserRows;
       public List<ProjectRole> ProjectRoles;
}
public class ProjectUserRowModel
{
       public Guid Guid { get; set; }
       public string Name { get; set; }
       public string Email { get; set; }
       public Guid RoleId { get; set; }
}

这里是视图(为简洁起见,只是 form/table):

<div class="row">
    <div class="col-md-4">
        <form asp-action="ManageUsersSave" method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="ProjectId"/>
            <table>
                @for (var i=0; i < Model.ProjectUserRows.Count(); i++)
                {
                    <tr>
                        <input type="hidden" asp-for="@Model.ProjectUserRows[i].Guid" />
                        <td>
                            <input type="hidden" asp-for="@Model.ProjectUserRows[i].Name" />
                            @Model.ProjectUserRows[i].Name
                        </td>
                        <td>
                            <input type="hidden" asp-for="@Model.ProjectUserRows[i].Email" />
                            @Model.ProjectUserRows[i].Email
                        </td>
                        <td>
                            <select asp-for="@Model.ProjectUserRows[i].RoleId" asp-items="@(new SelectList(Model.ProjectRoles, "ProjectRoleId", "Name", @Model.ProjectUserRows[i].RoleId))">
                                <option value="">-- Project Role</option>
                            </select>
                        </td>
                        <td>
                            <a asp-action="DeleteProjectUser" asp-route-id="@Model.ProjectUserRows[i].Guid" class="text-danger">Delete</a>
                        </td>
                    </tr>
                }
            </table>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary"/>
            </div>
        </form>
    </div>
</div>

这是方法的声明:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ManageUsersSave([Bind("ProjectId,ProjectUserRows,ProjectRoles")]ManageUsersViewModel manageUsersViewModel)

除了处理对象时的值是空值外,我根本找不到任何错误。

如果指定 FromBody 而不是 Bind 会发生什么情况?

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ManageUsersSave([FromBody]ManageUsersViewModel manageUsersViewModel)

我注意到您在 ManageUsersViewModel 模型中使用了 fields, not properties
模型活页夹仅适用于 properties.

还有关于 [Bind] 属性的注释。我不是很熟悉它,它是否识别表单数据。如果它不起作用,请使用 [FromForm].