在ASP.NET中使用JSON和AJAX从SQL数据库检索数据

时间:2018-10-10 17:33:43

标签: c# json ajax

我有一个Web方法,可以在其中执行SQL命令(测试后将写入存储的过程)并分配这些值。

然后我尝试将数据传递给AJAX函数并填充文本框,但它返回[object Object]。我认为它没有达到我的网络方法,因为它没有达到断点。我已确保AJAX网址正确。

这就是我所拥有的:

C#

public class Club {
    public int ClubID { get; set; }
    public string ClubName { get; set; }
    public string ClubEmail { get; set; }
    public string ClubPassword { get; set; }
}

[System.Web.Services.WebMethod]
public void ClubInfo(int ClubId) 
{
    Club club = new Club();

    SqlConnection con = new SqlConnection(
    WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
    con.Open();
    SqlCommand cmd = new SqlCommand("select * from [dbo].[tb_ClubDetails] where ClubID = @ClubID", con);
    cmd.Parameters.AddWithValue("@ClubID", ClubId);
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read()) {
        club.ClubID = Convert.ToInt32(rdr["ClubID"]);
        club.ClubName = rdr["ClubName"].ToString();
        club.ClubEmail = rdr["ClubEmail"].ToString();
        club.ClubPassword = rdr["ClubPassword"].ToString();
    }
    JavaScriptSerializer js = new JavaScriptSerializer();
    Context.Response.Write(js.Serialize(club));

}

AJAX

$(document).ready(function () {
    $("#btnRetrieve").click(function () {
        getData();
        return false;
    });
    function getData() {
        var clbId = $('#txtID').val();

        $.ajax({
            url: 'AddViewClub.aspx/ClubInfo',
            data: { ClubId: clbId },
            dataType: "json",
            method: 'post',
            success: function (data) {
                $('#txtClubName').val(data.ClubName);
                $('#txtEmail').val(data.ClubEmail);
                $('#txtPassword').val(data.ClubPassword);
            },
            error: function (err) {
                alert(err);
            }
        });

    }
});

请帮助我如何将数据成功地从Web方法传递到AJAX函数并填充文本框。谢谢。

1 个答案:

答案 0 :(得分:0)

我通过执行以下操作使其工作。但是,我不确定这是否是最佳做法。如果我可以改善下面的代码,请纠正我

    public class Club
    {
        public string ClubName { get; set; }
        public string ClubEmail { get; set; }
        public string ClubPassword { get; set; }
    }

    [WebMethod]
    public static List<Club> ClubInfo(string id)
    {
        SqlConnection con = new SqlConnection(
        WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
        con.Open();
        List<Club> clb = new List<Club>();
        SqlCommand cmd = new SqlCommand("select * from [dbo].[tb_ClubDetails] where ClubID = @ClubID", con);
        cmd.Parameters.AddWithValue("@ClubID", id);
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            clb.Add(new Club
            {
                //ClubID = Convert.ToInt32(rdr["ClubID"]),
                ClubName = rdr["ClubName"].ToString(),
                ClubEmail = rdr["ClubEmail"].ToString(),
                ClubPassword = rdr["ClubPassword"].ToString(),
            });

        }
        con.Close();
        return clb;
    }

AJAX

$(document).ready(function () {
    $("#btnRetrieve").click(function () {
        getData();
        return false;
    });
    function getData() {
        var clbId = $('#txtID').val();
        $.ajax({
            type: "POST",
            url: "AddViewClub.aspx/ClubInfo",
            data: "{'id': '" + clbId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });

    }
    function OnSuccess(response) {
        var clb = response.d;
        $(clb).each(function () {
            $('#txtClubName').val(this.ClubName);
            $('#txtEmail').val(this.ClubEmail);
            $('#txtPassword').val(this.ClubPassword);
        });
    }
});