【问题标题】:Model binding collection of Objects as one property of Model in ASP.Net Core MVC对象的模型绑定集合作为 ASP.Net Core MVC 中模型的一个属性
【发布时间】:2019-07-25 15:55:38
【问题描述】:

我有一个 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; }
}

在我的编辑视图中,我尝试将 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 是用于绑定ASP.NET Core Model Bind Collection of Unknown Length 这个问题中提到的非顺序索引的字符串。

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

我是用正确的方式还是建议我用更好的方式来做,以及我在哪里出错了。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-core


    【解决方案1】:

    你需要这样做:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 2020-03-14
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多