简体   繁体   中英

How to pass a dataTable from C# code behind to jQuery

I have string to pass as a table of data from C# code behind to jQuery. for that I am using two functions:

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

Client-side

$.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; returns 2 row and alert(response.d) is not showing anythig 在此处输入图片说明

I tried using $.map(data, function (listitem) function but no result .

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

Please help .!

Your array is there in the d property, so you can use the map function but using the data.d instead of just data .

Then the ListItem properties are Text and Value , so your code should look like this:

$.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");
    });
}

使用以下代码。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM