Returning Value(all fields) from Datatable to AJAX in ASP.NET C#

人盡茶涼 提交于 2021-02-07 10:50:29

问题


I've searched all over the net but I didn't find the answer maybe you guys can help. I am new to ASP.NET C#

My aspx.cs code

[WebMethod]
[ScriptMethod]
public static string GetData(int ID)
{
    string SQL = "Select ID, FirstName, MiddleName, LastName from tbl_demo1 where ID = '" + ID + "'";
    DataTable dt = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter(SQL, cn);
    da.Fill(dt);
    if(dt.Rows.Count > 0)
    {
        return dt.Rows[0].ItemArray[0].ToString();
    }
    return "";
}

Question:in this part

return dt.Rows[0].ItemArray[0].ToString();

In this part I want to return all fields(ID, FirstName, MiddleName, LastName) .. How would I do it?


回答1:


Here is the part of code that you asked:

if (dt.Rows.Count > 0)
{
   DataRow row = dt.Rows[0];
   string str = row["ID"].ToString() + row["FirstName"].ToString() + row["MiddleName"].ToString() + row["LastName"].ToString();
   return str;
}

If you want to return it as an KVP array, use like below

SortedList<string, string> rowObj = new SortedList<string, string>();
rowObj.Add("ID", row["ID"].ToString());
rowObj.Add("FirstName", row["FirstName"].ToString());
rowObj.Add("MiddleName", row["MiddleName"].ToString());
rowObj.Add("LastName", row["LastName"].ToString());
return (new JavaScriptSerializer().Serialize(rowObj));

Can be called using jQuery:

jQuery.ajax({
    type: "POST",
    url: "YourFileService.asmx/GetData",
    data: "{'ID':" + ID + "}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        if (typeof data.d != "undefined") {
            var res = JSON.parse(data.d);
            alert(res.FirstName)
        } else {
            if (window.console) {
                console.log('Unknown error,');
            }
        }
    },
    error: function (xhr, errorType, exception) {
        //raise an error
        alert(xhr.responseText);
    },
    failure: function (response) {
        //failure, raise an error
        alert(response.responseText);
    }
});


来源:https://stackoverflow.com/questions/50829387/returning-valueall-fields-from-datatable-to-ajax-in-asp-net-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!