ASP .NET Core 模型绑定

ASP .NET Core model binding

我正在使用 Visual Studio 16.4.6 并使用 SDK 2.2 开发 ASP .NET Web 应用程序。我的问题是在发出提交后我的模型中的嵌入对象被设置为空。这是一些细节。

class Photo {
    public int GardenId { get; set; }
    public string Filename { get; set; }
    public bool isDisplayed { get; set; }
}

class garden {
    public int Id { get; set; }
    public string Description { get; set; }
    public ICollection<Photo> Photos { get; set; }
}

传递到视图(用于编辑目的)的模型是花园。当数据进入视图时,所有内容都会正确填充,包括具有值的 ICollection 照片对象。该视图能够访问照片对象并显示相关文件。但是,当按下提交按钮以处理更改时,传回控制器方法的模型的 Photos 对象具有空值。本质上,当模型被传递回控制器时,Photos 对象被删除。其他花园对象属性随更新一起出现。即使只按下提交按钮并且没有编辑任何属性,也会发生同样的事情。非常感谢任何建议。

The view is able to access the Photos object and display the associated files. However, when the submit button is pressed to process changes, the model passed back into the controller method has a null value for the Photos object.

为了解决上述发布数据未绑定属性的问题,请使用浏览器F12开发者工具网络工具检查您发布的表单数据是否如下所示。

您可以参考以下代码片段在您的表单中显示Photos相关信息。

@model garden

@{
    ViewData["Title"] = "Edit";
    var Photos = Model.Photos.ToList();
}

<h1>Edit</h1>

<h4>garden</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Id" class="control-label"></label>
                <input asp-for="Id" class="form-control" />
                <span asp-validation-for="Id" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            @for (int i = 0; i < Model.Photos.Count(); i++)
            {
                <input type="hidden" asp-for="@Photos[i].GardenId" />
                <div class="form-group">
                    <label asp-for="@Photos[i].Filename" class="control-label"></label>
                    <input asp-for="@Photos[i].Filename" class="form-control" />
                </div>
                <div class="form-group">
                    <label asp-for="@Photos[i].isDisplayed" class="control-label"></label>
                    <input asp-for="@Photos[i].isDisplayed" class="form-control" />
                </div>
            }
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

测试结果