c# - 对象的模型绑定(bind)集合作为 ASP.Net Core MVC 中模型的一个属性

标签 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; }
}

和 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 包含的内容。

enter image description here

我使用它的方式是否正确,或者建议我使用更好的方式,以及我哪里出错了。

最佳答案

你需要这样做:

@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/

相关文章:

c# - 如何使用 SignalR(单独的域)进行表单例份验证?

asp.net-mvc - 用于 YUI 控件(雅虎用户界面)的 ASP.NET MVC HtmlHelper 扩展?

asp.net-mvc - 在asp.net MVC中缓存部分 View

c# - 整洁架构和 Asp.Net 核心标识

asp.net-core - 使用自定义 JSON.NET JsonConverter 从 DescriptionAttribute 反序列化枚举停止工作

.net - 有没有办法使用新的 .NET SDK 项目系统禁用 globbing?

c# - 使用指针和 ref 关键字引用值有什么区别

c# - 这个 log4net 实现我做错了什么?

c# - 主细节 MVVM WPF 不工作

asp.net-mvc - 可编辑的 "GridView"像 ASP.NET MVC 中的控件