Friday, 9 August 2013

Passing Dynamic Collection Member Manually through Html.BeginForm Method

Let's say we have a model with a collection type member that is populated dynamically on client side and we want to pass them automatically to controller by using Html.BeginForm(). We can manually add html input elements with some conventions to allow the collection to be passed.
The input element must have:
- id attribute like 'CollectionName_IndexNumber__PropertyName'
- and name attribute like 'CollectionName[IndexNumber].PropertyName'

For example, if we have:
public class InvoiceDto
{
 public int InvoiceId { get; set; }
 public string Name { get; set; }    
 public string Description { get; set; }

 public IList<ItemSellingDto> Items { get; set; }
}

public class ItemSellingDto
{
 public int ItemSellingId { get; set; }
 public int ItemId { get; set; }
 public Int16 Quantity { get; set; }     
 public decimal Price { get; set; }
 public int InvoiceId { get; set; }
}
and we would like to add each collection member (ItemSellingDto) to an html table element inside Html.BeginForm() dinamically using JavaScript (see my previous post to see the example layout), then the script would look like something like:
function addRow(response) {
 var tableRows = $('#tblItemSellings tr');
 var tr;
 tr = $('<tr/>');
 tr.append("<td>" + response.ItemName + "</td>");
 tr.append("<td>" + response.Quantity + "</td>");
 tr.append("<td>" + response.Price + "</td>");

    // the first row is for table headers
 tr.append("<td><input type='hidden' id='Items_" + (tableRows.length - 1) + "__ItemId' name='Items[" + (tableRows.length - 1) + "].ItemId' value='" + response.ItemId + "'/></td>");
 tr.append("<td><input type='hidden' id='Items_" + (tableRows.length - 1) + "__Quantity' name='Items[" + (tableRows.length - 1) + "].Quantity' value='" + response.Quantity + "'/></td>");
 tr.append("<td><input type='hidden' id='Items_" + (tableRows.length - 1) + "__Price' name='Items[" + (tableRows.length - 1) + "].Price' value='" + response.Price + "'/></td>");

 $('#tblItemSellings').append(tr);
}

No comments: