Reputation: 562
I have a following table using MVC that shows number of items the user has.
<table border = "1" id="tblItems">
<%
var itemnum = 1;
foreach (var item in Model.Items)
{%>
<tr>
<td colspan="2" bgcolor="Silver"><strong>Item#<%=itemnum%></strong></td>
<td><%=Html.ActionLink("Delete", "DeleteItem", "Item", new { id = item.ID })%></td>
</tr>
<tr>
<td><strong>Name:</strong></td>
<td><%=Html.TextBox("ItemName_" + itemnum, item.Name)%></td>
</tr>
<tr>
<td><strong>Description:</strong></td>
<td><%=Html.TextBox("ItemDescription_" + itemnum, item.Description)%></td>
</tr>
<%itemnum++;
} %>
</table>
I will have a button that will Add New Item that will dynamically add identical structure.
Also, How would I assign a unique ID to each of the input controls? In my controller I need to loop through total number of items and get a value from each input control by Request.Form.Get("Name_" + i);
Any ideas on what is the best way to do this using JQuery?
Thanks for all the suggestions!
Upvotes: 0
Views: 438
Reputation: 22485
user(then a big number) :)
take a look at jqote (a jquery templating library). very small and can do exactly as you mention above. in fact, here's a small example doing just what you're after:
http://hackingon.net/post/jQuery-client-side-templates-with-jqote-and-AspNet-MVC.aspx
good luck - i've used it with great success.
jim
Upvotes: 2
Reputation: 37547
You can use jQuery to duplicate the last row:
$("#tblItems tr:last").clone().appendTo("#tblItems");
But that will carry over your inputs
with the same names as the last row, not a great out-of-the-box solution. You can add some extensive jQuery manipulation to re-name the inputs, or, as Dan Diplo pointed out, there are some jQuery extensions that can do this for you.
Upvotes: 2
Reputation: 25339
You can do this in raw jQuery using the .clone() method, but as Chris Pebble points out it doesn't rename your element names and Ids. However, there are a couple of jQuery plug-ins that help make this easy, so check out:
http://plugins.jquery.com/project/dupeIt
"dupeIt is a jquery plugin that allows you to duplicate and remove DOM elements and their children with one click. dupeIt smartly renames duplicated elements by appending the iteration number, ex. "txt_mytextfield" duplicate would be "txt_mytextfield2".
http://plugins.jquery.com/project/clonefield
"jQuery.cloneField is a plugin that provides you with easy, dynamic form field (or any other DOM element, really) duplication and removal."
Upvotes: 0