微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 当删除中间的一个项目时,如何绑定ASP.NET MVC中的对象列表

我在将模型绑定到MVC中的列表时遇到问题.我的页面具有动态添加删除文本框的功能.我的页面 HTML将是
<form id="prdt">
    <div id="div_0"> <input type="text" name="products[0].Name" value="Coffee"/><button id="0" onclick="return DeleteLocation(this.id)">Delete</button></div>
    <div id="div_1"> <input type="text" name="products[1].Name" value="Tea" /><button id="1" onclick="return DeleteLocation(this.id)">Delete</button></div>
    <div id="div_2"> <input type="text" name="products[2].Name" value="Cola" /><button id="2" onclick="return DeleteLocation(this.id)">Delete</button></div>
    <div id="div_3"> <input type="text" name="products[3].Name" value="Pepsi" /><button id="3" onclick="return DeleteLocation(this.id)">Delete</button></div>
</form>

下面是删除文本框的代码

<script type="text/javascript">
    function DeleteLocation(id) {           
       $("#div_" + id).remove();
    }
</script>

但是当我删除“可乐”文本框并做一个ajax帖子时,我的列表中只有咖啡和茶(Controller Action Post).即列表中省略了最后一个

同样,当我删除“茶”文本框并做一个ajax帖子时,我只能获得咖啡.即列表中不包括其他三个值.

我认为列表与List索引绑定.是否有任何方法可以获取所有值,即使其中的任何项目被删除.

解决方法

可以通过添加名为products.Index的特殊字段来完成,其中包含下一个索引的值.您需要为每个新索引重复此操作:
<form id="prdt">
    <div id="div_0">
        <input type="hidden" name="products.Index" value="0" />
        <input type="text" name="products[0].Name" value="Coffee"/>
        <button id="0" onclick="return DeleteLocation(this.id)">Delete</button>
    </div>
    <div id="div_1"> 
        <input type="hidden" name="products.Index" value="1" />
        <input type="text" name="products[1].Name" value="Tea" />
        <button id="1" onclick="return DeleteLocation(this.id)">Delete</button>
    </div>
    <div id="div_2"> 
        <input type="hidden" name="products.Index" value="2" />
        <input type="text" name="products[2].Name" value="Cola" />
        <button id="2" onclick="return DeleteLocation(this.id)">Delete</button>
    </div>
    <div id="div_3"> 
        <input type="hidden" name="products.Index" value="3" />
        <input type="text" name="products[3].Name" value="Pepsi" />
        <button id="3" onclick="return DeleteLocation(this.id)">Delete</button>
    </div>
</form>

您可以在this article,“非顺序指数”部分找到更多信息

原文地址:https://www.jb51.cc/csharp/101050.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐