模型绑定对象集合作为 ASP.Net Core MVC 中模型的一个属性

Ram*_*mar 4 c# asp.net-mvc asp.net-core

我有一个 PostEditViewModel 类

 public class PostCreateViewModel
{
    public int PostId { get; set; }
    public string Title { get; set; } 
    public string Body { get; set; } 

    public string Descrition { get; set; } 
    public string Category { get; set; }

    public List<IFormFile> Images { get; set; } 
    public List<ImagePath> ExistingPhotoPaths { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和 ImagePath 类

public class ImagePath
{
    public int ID { get; set; }
    public string Path { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在我的编辑视图中,我尝试将 ExistingPhotoPaths 属性隐藏为

<input hidden asp-for="PostId" />

    @foreach (var path in Model.ExistingPhotoPaths)
    {
        i = i++;
        string x = val + i.ToString();
        <input type="hidden" name="ExistingPhotoPaths.Index" value="@x" />
        <input type="hidden" name="ExistingPhotoPaths[@x].Key" value="@path.ID" />
        <input type="hidden" name="ExistingPhotoPaths[@x].Value" value="@path.Path" />
    }
Run Code Online (Sandbox Code Playgroud)

其中 val 是用于绑定ASP.NET Core Model Bind Collection of Unknown Length这个问题中提到的非顺序索引的字符串。

但使用此方法我的 ExistingPhotoPaths 属性也返回 null 集合。即假设当 get 请求 ExistingPhotoPaths 在 post 请求中包含 3 个 ImagePath 对象时,它返回 3 个空对象的数组,请参见下图,在 post 请求中查看 ExistingPhotoPaths 包含的内容。

在此输入图像描述

我是否以正确的方式使用它,或者建议我更好的方式来做到这一点以及我的方式出错的地方。

Chr*_*att 5

你需要这样做:

@for (var i = 0; i < Model.ExistingPhotoPaths.Count; i++)
{
    <input type="hidden" asp-for="ExistingPhotoPaths[i].ID" />
    <input type="hidden" asp-for="ExistingPhotoPahts[i].Path" />
}
Run Code Online (Sandbox Code Playgroud)

您当前使用的语法用于绑定到字典,而不是对象列表,并且 foreach 在这里不起作用,因为 Razor 需要整个模型表达式路径来构建正确的输入名称。