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

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

概述我在将模型绑定到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 我在将模型绑定到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,“非顺序指数”部分找到更多信息

总结

以上是内存溢出为你收集整理的c# – 当删除中间的一个项目时,如何绑定ASP.NET MVC中的对象列表全部内容,希望文章能够帮你解决c# – 当删除中间的一个项目时,如何绑定ASP.NET MVC中的对象列表所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1247334.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存