我有一个表单,用户可以从下拉框动态地将条目添加到html表中。每个条目都添加为自己的行。这在javascript中很容易完成:
function addProduct(int type) {
var product = getProduct(type); // The method just fetches the product from the database
$('selectedProductsTable').append("<tr><td>" + product.Name +"</td><td>" + product.Quantity + "</td></tr>")
}
在第二步中,需要将表的内容发布到控制器以进行进一步处理。将我添加的产品作为表格行添加的一般最佳做法是什么?我可以迭代selectedProductsTable的行,但这似乎有点容易出错。
另一方面,我会接受另一种方式来保留所选项目,以便我可以将它们发布到控制器。不幸的是,在会话或tempData中保存它们也不是一个好选择,因为选择完全在javascript中进行。
答案 0 :(得分:0)
只有INPUT和SELECT元素会被发布回服务器,因此您需要将每个值存储在隐藏字段中以使其恢复。您可以使用基于索引的方法回发数组,这很有效。 See this post
我写了blog post about dynamic client-side lists,这可能会有所帮助。它使用Kendo Core但不需要。
答案 1 :(得分:0)
在方法addProduct
中使用有关产品的数据填充数组:
var products=[];
function addProduct(int type) {
var product = getProduct(type); // The method just fetches the product from the database
products.push(product)
$('selectedProductsTable').append("<tr><td>" + product.Name +"</td><td>" +
product.Quantity + "</td></tr>")
}
然后用ajax发送它:
$.ajax({
url: 'your url',
type: 'POST',
dataType: 'json',
success: function (data) {
//TODO
},
data: JSON.stringify(products)
});