由于您无法在回发时读取动态表,因此我通常将所有行读入对象并将它们通过 WebMethod 或 WCF 服务传递回服务器。我对 Ajax 表单和传统回发表单都使用了相同的技术。
这是我所做工作的快速总结。
HTML
<table class="mediumTable" id="PartTable">
<thead>
<tr class="rowHeader">
<th>Part </th>
<th>Price </th>
<th>UOM </th>
<th>Apply Date </th>
<th>Remarks </th>
</tr>
</thead>
<tbody>
<tr>
<td>Part12345</td>
<td>0.298</td>
<td>1</td>
<td>5/31/2012</td>
<td></td>
</tr>
</tbody>
</table>
JavaScript
// Read a row in View Mode into a Cross Object
function GetRowAsObject(rowNum) {
var row = $('#PartTable tbody tr').eq(rowNum);
var cross = {};
cross.Part = row.find('td:eq(1)').text();
cross.Price = row.find('td:eq(2)').text();
cross.UOM = row.find('td:eq(3)').text();
cross.ApplyDate = row.find('td:eq(4)').text();
cross.Remarks = row.find('td:eq(5)').text();
return cross;
}
// Read all rows into Cross Object Array
function GetAllViewRowsAsCrossObjects() {
var parts = [];
$('#PartTable tbody tr').each(function (index, value) {
var part = GetRowAsObject(index);
parts.push(row);
});
return parts;
}
// Post all rows to the server and put into Cache
function PostTable() {
var batchId = getParameterByName('id');
var jsonRequest = { crosses: GetAllViewRowsAsCrossObjects(), batchId: batchId};
$.ajax({
type: 'POST',
url: 'PartsForm.aspx/SaveParts',
data: JSON.stringify(jsonRequest),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data, text) {
// Do Something
},
error:function (request, status, error){
// Do Something
}
});
代码背后
public partial class Part3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// This is a Ajax WebMethod that can be called via jQuery.
/// </summary>
/// <param name="crosses">Array of Cross Objects</param>
/// <param name="batchId">Batch number to apply to all parts</param>
/// <returns></returns>
[WebMethod]
public static bool SaveParts(List<Cross> crosses, int batchId)
{
// Save Parts to the DB
return true;
}
}
// Data Transfer Object, must match the object sent from the client
public class Cross
{
public string Part { get; set; }
public double Price { get; set; }
public int UOM { get; set; }
public DateTime ApplyDate { get; set; }
public string Remarks { get; set; }
}