简体   繁体   English

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

[英]Retrieve data from SQL database using JSON and AJAX in ASP.NET

I have a web method where I execute a SQL command (will write a stored proc. after test) and assign those values. 我有一个执行SQL命令的Web方法(测试后将写入存储的过程)并分配这些值。

I then try to pass the data to an AJAX function and populate the textboxes but it returns [object Object]. 然后,我尝试将数据传递给AJAX函数并填充文本框,但它返回[object Object]。 I think it doesn't reach my web method since it is not hitting the break point. 我认为它没有达到我的网络方法,因为它没有达到断点。 I have ensured that the AJAX url is correct. 我已确保AJAX网址正确。

This is what I have: 这就是我所拥有的:

C# 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 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);
            }
        });

    }
});

Please assist me how I can pass data successfully from web method to AJAX function and populate textboxes. 请协助我如何将数据成功地从Web方法传递到AJAX函数并填充文本框。 Thank you. 谢谢。

I got it to work by doing the following. 我通过执行以下操作使其工作。 However, I am not sure if it's best practice. 但是,我不确定这是否是最佳做法。 Please correct me if I can improve my code below 如果我可以改善下面的代码,请纠正我

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AJAX + ASP.net从Sql Server检索数据? - AJAX + ASP.net to retrieve data from Sql Server? 使用asp.net从SQL数据库检索二进制数据 - retrieve Binary Data from SQL Database with asp.net 如何使用json和ajax从asp.net中的sql server数据库填充列表 - how to populate list from sql server database in asp.net using json and ajax 从特定 Id 的数据库中检索所有数据或事务的 SQL 语句,并在 asp.net 中的图形上绘制相同的图 - SQL statement to retrieve all data or transactions from database of a particular Id and plot same on a graph in asp.net ASP.NET MVC无法从本地SQL Server Express数据库检索数据 - ASP.NET MVC unable to retrieve data from local SQL Server Express database 如何使用 ASP.NET 从 SQL 服务器数据库中检索和显示 GridView 中的值 - How to retrieve and display values in GridView from SQL Server database in ASP.NET using C# How to retrieve a Json object from SQL procedure in ASP.NET using C#? - How to retrieve a Json object from SQL procedure in ASP.NET using C#? 从asp.net中的数据库检索数据的超链接 - hyperlink to retrieve data from a database in asp.net ASP.NET MVC将数据从数据库检索到DropDownList - ASP.NET MVC Retrieve Data from Database to DropDownList 从 SQL 中检索单条数据并在 ASP.NET 中显示 - Retrieve single piece of data from SQL and display in ASP.NET
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM