索引损坏的对象的 Razor Pages 模型绑定列表

Razor Pages Model Binding List of objects with broken index

我基本上有一个表单,我在其中添加和删除项目并使用模型绑定将它们绑定到列表。这适用于修改字段和添加新项目,但是当我尝试删除它们时,我破坏了索引并且绑定的列表不包括所有项目。

我生成的标记看起来像这样:

<table>
    <tbody>
        <tr>
            <input type="text" name="devices[0].id"  value="8574" />
            <input type="text" name="devices[0].type"  value="Type1" />
        </tr>
        <tr>
            <input type="text" name="devices[1].id"  value="4385" />
            <input type="text" name="devices[1].type"  value="Type2" />
        </tr>
        <tr>
            <input type="text" name="devices[2].id"  value="9486" />
            <input type="text" name="devices[2].type"  value="Type1" />
        </tr>
        ...
    </tbody>
</table>

我的模型绑定是这样的:

public IActionResult OnPostSave(List<Device> devices){
    // ... do something
}

现在我让用户通过 javascript 简单地从 table 中删除行然后将更新的表单发送到我的 OnPostSave() 来操作表单数据。现在,例如删除 ID 为“4385”的行时,该行之后的所有项目都不会被绑定。关于这个来自 Scott Hanselman 的 post 这绝对是有道理的,但我想知道是否有解决这个问题的方法?最好在将其发布到服务器之前不修改js中的表单。

提前致谢!

模型绑定器支持非顺序索引。您必须使用显式索引,该索引由集合中每个项目的名为 propertyname.Index 的隐藏字段表示。我将使用您示例中的设备键值进行说明,但索引值可以是任何内容,包括字符串、guid 等:

    <tr>
        <input type="hidden" name="devices.Index" value="8574" />
        <input type="text" name="devices[8574].id"  value="8574" />
        <input type="text" name="devices[8574].type"  value="Type1" />
    </tr>
    <tr>
        <input type="hidden" name="devices.Index" value="4385" />
        <input type="text" name="devices[4385].id"  value="4385" />
        <input type="text" name="devices[4385].type"  value="Type2" />
    </tr>
    <tr>
        <input type="hidden" name="devices.Index" value="9486" />
        <input type="text" name="devices[9486].id"  value="9486" />
        <input type="text" name="devices[9486].type"  value="Type1" />
    </tr>

您可以在此处阅读有关使用顺序和非顺序索引绑定到集合的更多信息:https://www.learnrazorpages.com/razor-pages/model-binding#binding-complex-collections