使用 ajax 方法 C# 从 SQL Server 数据库中检索数据

本文关键字:数据库 检索 数据 Server SQL ajax 方法 使用 | 更新日期: 2023-09-27 18:33:56

我是C#和javacript的新手。我正在Visual Studio上做我的第一个程序,从SQL Server数据库中检索数据时遇到了一个问题。

我想从 SQL Server 检索数据并使用 ajax 方法将其转换为 Json。但是当我启动我的网页时,我只能看到空的表,所以我认为我没有一个好的方法来连接到我的数据库。

这是我WebMethod用于检索数据并转换为 JSON 的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using Newtonsoft.Json;
public partial class _Default : System.Web.UI.Page
{    
    protected void Page_Load(object sender, EventArgs e)
    {                         
    }
    [WebMethod]
    public static string LoadData()
    {
        string strcon = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("select * from kit", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);            
        return JsonConvert.SerializeObject(ds.Tables[0]); 
    }  

请我需要你的帮助,我已经在这个程序上做了几天。感谢您的帮助。

使用 ajax 方法 C# 从 SQL Server 数据库中检索数据

您的 CommandType 应该是 Text 而不是 StorageProcedure,因为您使用的是字符串 SQL 命令而不是存储过程。