c# - How to bind list of objects in ASP.NET MVC when one item in between is deleted -


i have issue while binding model list in mvc. page has functionality add , delete text-box dynamically. page 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> 

below code delete textbox

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

but when delete "cola" text-box , ajax post getting coffee , tea in list(controller action post). i.e last 1 omitted in list

similarly when delete "tea" text-box , ajax post getting coffee only. i.e other 3 values excluded in list.

i think list binding on list index. there way values if item in between deleted.

it can done adding special field named products.index value of next index be. need repeat each new 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> 

you can find more info in this article, section 'non-sequential indices'


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -