Javascript ASP.NET以编程方式从AJAX插入表行
我在cshtml页面中有一个简单的HTML表。它基本上是一个单列,我想通过编程从ajax调用的结果中插入行 返回的桶是字符串[],其中桶[0]=桶1;桶[1]=桶2。。。等等我想让每个浴缸在我的桌子上排成一行 这是控制器中的C:Javascript ASP.NET以编程方式从AJAX插入表行,javascript,ajax,asp.net-mvc,Javascript,Ajax,Asp.net Mvc,我在cshtml页面中有一个简单的HTML表。它基本上是一个单列,我想通过编程从ajax调用的结果中插入行 返回的桶是字符串[],其中桶[0]=桶1;桶[1]=桶2。。。等等我想让每个浴缸在我的桌子上排成一行 这是控制器中的C: [HttpPost] // can be HttpGet public ActionResult NotTested(string siteid, string testdate) { int i = 0;
[HttpPost] // can be HttpGet
public ActionResult NotTested(string siteid, string testdate)
{
int i = 0;
//this could be populated first by reading for this "site" how many tubs to be expected
string[] UnTested = new string[8];
SqlConnection conn = new SqlConnection(@"Server=****;Database=****;User Id=****;Password=****;");
SqlCommand cmd = new SqlCommand("select * from TubsNotTested(@siteid,@testdate)", conn);
cmd.Parameters.AddWithValue("@siteid",siteid);
cmd.Parameters.AddWithValue("@testdate", testdate);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
for(i=0; i<dt.Rows.Count; i++)
{
UnTested[i] = dt.Rows[i][0].ToString();
}
return Json(new
{
Tubs = UnTested,
}, JsonRequestBehavior.AllowGet);
}
请尝试以下操作:
var table = document.getElementById("notestedtable");
for (var i = 0; i < result.Tubs.length; i++) {
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell.innerHTML = result.Tubs[i];
}
请尝试以下操作:
var table = document.getElementById("notestedtable");
for (var i = 0; i < result.Tubs.length; i++) {
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell.innerHTML = result.Tubs[i];
}
将ajax成功回调修改为
success: function (result) {
$.each(result.Tubs, function(index, item) {
var cell = $('<td></td>').text(item); // create the table cell
var row = $('<tr></tr>').append(cell); // create the table row
$('#notestedtable').append(row); // append the row to the table
});
}
旁注:最好包括var table=$'notestedtable';在脚本顶部缓存元素,然后使用table.appendrow;因此,避免再次遍历DOM。将ajax成功回调修改为
success: function (result) {
$.each(result.Tubs, function(index, item) {
var cell = $('<td></td>').text(item); // create the table cell
var row = $('<tr></tr>').append(cell); // create the table row
$('#notestedtable').append(row); // append the row to the table
});
}
旁注:最好包括var table=$'notestedtable';在脚本顶部缓存元素,然后使用table.appendrow;因此,避免再次遍历DOM。这应该可以,但是您应该使用document.ready而不是document.onload,最好使用$function{…notationI已经实现了这一点,并将alertitem放在$'notestedtable.appendrow;下,我得到了Tub 6,,,,,,但表中没有显示任何内容?console.log$'notestedtable.length;return?应该可以正常工作。您确定结果是和数组吗?我将为您创建一个小提琴shortly@StephenMuecke-我已将我的原始帖子编辑到显示AJAX调用背后的C代码…这应该可以工作,但是您应该使用document.ready而不是document.onload,最好使用$function{…notationI已经实现了这一点,并将alertitem放在$'notestedtable.appendrow;下,我得到了Tub 6,,,,,,但表中没有显示任何内容?console.log$'notestedtable.length;return?应该可以正常工作。您确定结果是和数组吗?我将为您创建一个小提琴shortly@StephenMuecke-我已将我的原始帖子编辑到显示AJAX调用背后的C代码。。。