我有一个 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; }
}
和 ImagePath 类
public class ImagePath
{
public int ID { get; set; }
public string Path { get; set; }
}
在我的编辑 View 中,我尝试将 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" />
}
其中 val 是用于绑定(bind) ASP.NET Core Model Bind Collection of Unknown Length 中提到的非顺序索引的字符串这个问题。
但是使用此方法我的 ExistingPhotoPaths 属性也返回 null 集合。即假设在获取请求时,ExistingPhotoPaths 在发布请求时包含 3 个 ImagePath 对象,它返回 3 个空对象的数组,请参见下图,在发布请求时查看 ExistingPhotoPaths 包含的内容。
我使用它的方式是否正确,或者建议我使用更好的方式,以及我哪里出错了。
最佳答案
你需要这样做:
@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" />
}
您当前使用的语法用于绑定(bind)到字典,而不是对象列表,foreach 在这里不起作用,因为 Razor 需要整个模型表达式路径来构建正确的输入名称。
关于c# - 对象的模型绑定(bind)集合作为 ASP.Net Core MVC 中模型的一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57206013/