【问题标题】:How to pass a dataTable from C# code behind to jQuery如何将数据表从 C# 代码后面传递给 jQuery
【发布时间】:2017-11-23 12:10:16
【问题描述】:

我有字符串作为数据表从后面的 C# 代码传递给 jQuery。 为此,我使用了两个功能:

C#

[System.Web.Services.WebMethod(EnableSession = true)]
public static List<ListItem> GetImageArray(string AccNo)
{
    string result = string.Empty;
    var obj = new AccountTransaction();

    DataTable dt = obj._commonobj.SearchAccNo(AccNo, "", "GETIMAGE");
    List<ListItem> datas = new List<ListItem>();

    if (dt.Rows.Count > 0)
    {
        foreach (DataRow row in dt.Rows)
        {
            string CustImg = Convert.ToString(row["Customer Image"]);
            string SignImg = Convert.ToString(row["Sign"]);

            ListItem listitem = new ListItem(CustImg, SignImg);
            datas.Add(listitem);                  
        }
    }
    return datas;
}

客户端

$.ajax({
    type: "POST",
    url: "AccountTransaction.aspx/GetImageArray",
    data: "{'AccNo':'" + col1 + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnImgSuccess,
    failure: function (response) {
        alert(response.d);
    }
});

function OnImgSuccess(response) {
    alert(response.d);
    });
}

return datas; 返回 2 行,alert(response.d) 没有显示任何内容

我尝试使用$.map(data, function (listitem) 函数但没有结果。

 $.map(data, function (listitem) {
    $('<tr> <td>' + listitem.CustImg + '</td> <td>' + listitem.SignImg + ' </td> </tr>').appendTo(".tblData");
 });

请帮忙!

【问题讨论】:

  • 您非常接近解决方案。在开发者控制台中检查你从控制器获得的对象,你会发现它。
  • @Doruk C# 函数看起来不错,因为我在变量 datas 上有 2 行值,但在成功函数上没有得到这些值..
  • offtopic: 'data' 是复数,没有'datas' 这样的词(你可以使用'dataList')
  • 永远不要在对象上使用alert - 你只会得到[object Object]。使用console.log(response) 并查看控制台。您在警报中获得两个 [object] 的事实表明它返回的数组/列表很好。
  • 网络选项卡对您的 ajax 查询有何说明?

标签: javascript c# jquery asp.net ajax


【解决方案1】:

您的数组位于d 属性中,因此您可以使用map 函数,但使用data.d 而不仅仅是data

那么ListItem 属性是TextValue,所以你的代码应该是这样的:

$.ajax({
    type: "POST",
    url: "AccountTransaction.aspx/GetImageArray",
    data: "{'AccNo':'" + col1 + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: onImgSuccess,
    failure: function (response) {
        alert(response.d);
    }
});

function onImgSuccess(data) {
    $.map(data.d, function (listitem) {
        $('<tr> <td>' + listitem.Text + '</td> <td>' + listitem.Value + ' </td> </tr>').appendTo(".tblData");
    });
}

【讨论】:

    【解决方案2】:

    使用以下代码。

    alert($.parseJSON(response.d));
    

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 2012-08-21
      相关资源
      最近更新 更多