ASP.NET以编程方式从AJAX插入表行

时间:2015-06-21 10:18:19

标签: javascript ajax asp.net-mvc

我在cshtml页面中有一个简单的HTML表格。它基本上是一个列,我想以编程方式从ajax调用的结果中插入行。

        <table class="table" id="notestedtable">
        <tr>
            <th>
                Not Tested
            </th>
        </tr>
        <tr>
            <td>
                Unit#1 
            </td>
        </tr>
        </table>

我使用document.onload = NotTested("Site 001", "17/06/2015");来调用函数,然后执行ajax

function NotTested(SiteId,TestDate) {

    $.ajax({
        url: '/Home/NotTested',
        type: 'POST',
        contentType: 'application/json;',
        data: JSON.stringify({
            siteid: SiteId, testdate: TestDate
        }),
        success: function (result) {
            for (var i = 0; i < result.Tubs.length; i++) {

                alert(result.Tubs);
            }
        }
    })
}

返回的Tubsstring[] Tubs[0] = "Tub 1"; Tubs[1] = "Tub 2" ...,依此类推。我希望每个Tub[]在我的表格中形成一行。

这是控制器中的C#:

       [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);
    }

2 个答案:

答案 0 :(得分:3)

将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.append(row);以避免再次遍历DOM。

答案 1 :(得分:1)

尝试以下方法:

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];
        }