【问题标题】:Trying to bind data from SQL Server using a C# web method(ASP .NET) to a grid coded using jQuery尝试使用 C# Web 方法(ASP .NET)将数据从 SQL Server 绑定到使用 jQuery 编码的网格
【发布时间】:2020-05-09 16:34:17
【问题描述】:

我希望我的问题标题具有描述性,有助于您理解我所面临的问题。我是编程新手,我知道我面临的问题是只有初学者才会遇到的问题。请帮帮我。请耐心等待,因为这是一个很长的描述。我知道,在这个社区中的大多数人都是非常有经验的程序员,不需要如此详细的方法,但我无意浪费你的时间,我相信通过提供如此详细的描述,你会能够更好地帮助我。现在关于这个问题,我正在尝试使用 jQuery 构建一个网格:

https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/index.htm#demos/jqxgrid/defaultfunctionality.htm

我已经使用上面链接中的源代码来构建网格,但是当我运行程序时,数据没有显示出来。我确信问题出在 jQuery 上,因为我已经单独运行了我的 Web 服务,它连接到 SQL Server 并以 JSON 数组的形式显示输出。

我在 Visual Studio 2019 上将解决方案分为三个项目:

  1. PracticeValidation 项目 - 包含 3 个 .aspx c# Web 表单。一个用于主页,另一个用于配方表单,第三个用于员工表单。
  2. WebServicesFunctionality 项目 - 包含一个 .asmx Webservice 文件,该文件包含 2 个 Web 方法(一个用于配方表单,另一个用于员工表单)以将列表形式的数据序列化为 JSON 数组。请在下面找到 Web 服务的代码。
[System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string GetRecipe()
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            string recipeList = String.Empty;
            List<FormGeneratorClass.FormGeneratorVar.RecipeVar> recipeCatcher = new List<FormGeneratorClass.FormGeneratorVar.RecipeVar>();
            recipeCatcher = FormGeneratorClass.FormGeneratorVar.ExecuteRecipeList();
            if (recipeCatcher != null && recipeCatcher.Count > 0)
            {
                recipeList = js.Serialize(recipeCatcher);
            }
            else
                recipeList = js.Serialize("No recipes!");
            return recipeList;
        }

        [WebMethod]
        public string GetEmp()
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            string EmployeeList = String.Empty;
            List<FormGeneratorClass.FormGeneratorVar.EmpVar> employeeCatcher = new List<FormGeneratorClass.FormGeneratorVar.EmpVar>();
            employeeCatcher = FormGeneratorClass.FormGeneratorVar.ExecuteEmployeeList();
            if (employeeCatcher != null && employeeCatcher.Count > 0)
            {
                EmployeeList = js.Serialize(employeeCatcher);
            }
            else
                EmployeeList = js.Serialize("No recipes!");
            return EmployeeList;
        }
    }
  1. FormGeneratorClass 项目:该项目包含一个负责与 SQL Server 交互的 c# 类文件。我在下面的这个文件中附加了代码。
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FormGeneratorClass
{
    public class FormGeneratorVar
    {
        public class RecipeVar
        {
            public int Recipe_Id { get; set; }
            public string Recipe_Name { get; set; }
        }

        public class EmpVar
        {
            public int Emp_Id { get; set; }
            public string Emp_FirstName { get; set; }
            public string Emp_LastName { get; set; }
        }

        public static List<RecipeVar> ExecuteRecipeList()
        {
            List<RecipeVar> listRecipe = new List<RecipeVar>();
            string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(strConnString))
            {
                string sqlSelectAllQuery = "SELECT * FROM Tbl_Recipe";
                SqlCommand cmd = new SqlCommand(sqlSelectAllQuery, con);
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    RecipeVar recipe = new RecipeVar();
                    recipe.Recipe_Id = !(rdr["recipe_id"] == DBNull.Value) ? Convert.ToInt32(rdr["recipe_id"]) : 0;
                    recipe.Recipe_Name = !(rdr["recipe_name"] == DBNull.Value) ? Convert.ToString(rdr["recipe_name"]) : string.Empty;
                    listRecipe.Add(recipe);
                }
                con.Close();
            }
            return listRecipe;
        }

        public static List<EmpVar> ExecuteEmployeeList()
        {
            List<EmpVar> listEmployee = new List<EmpVar>();
            string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(strConnString))
            {
                string sqlSelectAllQuery = "SELECT * FROM Tbl_Emp";
                SqlCommand cmd = new SqlCommand(sqlSelectAllQuery, con);
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    EmpVar employee = new EmpVar();
                    employee.Emp_Id = !(rdr["emp_id"] == DBNull.Value) ? Convert.ToInt32(rdr["emp_id"]) : 0;
                    employee.Emp_FirstName = !(rdr["emp_firstName"] == DBNull.Value) ? Convert.ToString(rdr["emp_firstName"]) : string.Empty;
                    employee.Emp_LastName = !(rdr["emp_lastName"] == DBNull.Value) ? Convert.ToString(rdr["emp_lastName"]) : string.Empty;
                    listEmployee.Add(employee);
                }
                con.Close();
            }
            return listEmployee;
        }
    }
}

我将WebServicesFunctionality项目(pt.2)设置为启动项目,并将得到的结果截图供大家参考

  1. The web service is loaded on my local browser

  2. The output after the employee web method gets invoked

  3. The output after the recipe web method gets invoked

现在我相信所有阅读这篇文章的人都会更清楚地了解我想要做什么。所以现在我将附上员工 .aspx 页面的代码。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmployeeRecord.aspx.cs" Inherits="PracticeValidation.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Record of employees</title>
    <meta name="description" content="JavaScript Grid with rich support for Data Filtering, Paging, Editing, Sorting and Grouping" />
    <link href="Scripts/jqx.base.css" rel="stylesheet" type="text/css"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1 maximum-scale=1 minimum-scale=1" />
    <script src="Scripts/jquery-1.11.1.min.js"></script>
    <script src="Scripts/jqxcore.js"></script>
    <script src="Scripts/jqxdata.js"></script>
    <script src="Scripts/jqxbuttons.js"></script>
    <script src="Scripts/jqxscrollbar.js"></script>
    <script src="Scripts/Menu.js"></script>
    <script src="Scripts/jqxcheckbox.js"></script>
    <script src="Scripts/jqxlistbox.js"></script>
    <script src="Scripts/jqxdropdownlist.js"></script>
    <script src="Scripts/jqxgrid.js"></script>
    <script src="Scripts/jqxgrid.sort.js"></script>
    <script src="Scripts/jqxgrid.pager.js"></script>
    <script src="Scripts/jqxgrid.selection.js"></script>
    <script src="Scripts/jqxgrid.edit.js"></script>
    <script src="Scripts/demos.js"></script>
    <script type="text/javascript">
            $(document).ready(function () {
                //Getting the source data with ajax GET request
                source = {
                    datatype: "json",
                    datafields: [
                        { name: 'EmpID' },
                        { name: 'EmpLastName' },
                        { name: 'EmpFirstName' }
                    ],
                    async: false,
                    record: 'Table',
                    url: 'WebService1.asmx/GetEmp',

                };
                var dataAdapter = new $.jqx.dataAdapter(source,
                    { contentType: 'application/json; charset=utf-8' }
                );
                $("#grid").jqxGrid({
                    source: dataAdapter,
                    theme: 'classic',
                    width: '100%',

                    columns: [
                        { text: 'EmpID', dataField: 'EmpID', width: 250, hidden: false },
                        { text: 'EmpLastName', dataField: 'EmpLastName', width: 150 },
                        { text: 'EmpFirstName', dataField: 'EmpFirstName', width: 180 },
                    ]
                });
            });
    </script>
</head>
<body class ='default'>
    <form id="form1" runat="server">
        <div>
            <h1>Welcome to the record of employees page</h1>
            <h4>Click <a href="HomePage.aspx">here</a> to go back to the main login page</h4>
        </div>
        <div id="grid">
        </div>
    </form>
</body>
</html>

我最后会附上我得到的输出截图。

员工记录.aspx页面的输出:

感谢所有阅读整篇文章并保持安全的人!

【问题讨论】:

  • 因为这似乎发出了一个 ajax 请求...您是否使用开发人员工具检查过哪些数据是从您的 Web 服务返回的?
  • @Lihka_nonem,我认为,您收到了响应,但您的数据是作为字符串返回的,而不是作为 json 对象。尝试在不序列化的情况下返回对象,看看会发生什么。
  • public List&lt;FormGeneratorClass.FormGeneratorVar.EmpVar&gt; GetEmp() 代替字符串,使对象的返回类型为List&lt;FormGeneratorClass.FormGeneratorVar.EmpVar&gt;
  • 您确认您的网络方法被浏览器请求命中了吗?
  • @Mephiztopheles 你能帮我看看我可以用来检查的资源吗?

标签: javascript c# jquery asp.net


【解决方案1】:

我知道我哪里出错了。数据没有按照我想要的方式绑定到网格有很多原因。我希望这对遇到相同问题的其他人有所帮助。

如果您按照我的方式创建解决方案,您需要解决的第一个问题是您需要创建一个代理 Web 服务来从 Web 服务获取数据。这是因为,Web 服务项目和 Web 表单项目在不同的端口上运行。因此,即使一切正常,您在发出 AJAX 请求时也会收到 404 错误。因此,从 Web 表单项目创建一个 Web 服务代理,否则就放弃创建一个单独的 Web 服务项目的想法。

我遇到的下一个问题很棘手,我花了很长时间才弄清楚。不管将来自 SQL 的数据序列化为 JSON,实际从 Web 服务发回的数据都是 XML。这是因为 Web 服务使用 SOAP,因此默认情况下数据传输的方法是 XML。如果您运行 Web 服务并观察数据,您将看到一个带有 XML 包装器的 JSON 字符串。如果您打开 Chrome 开发工具并查看内容类型,您会看到它返回 XML,无论您做什么,都无法阻止 Web 服务通过 AJAX 'GET' 请求返回 XML。那么你如何解决这个问题呢?两种方式:

方法 1:使用 Web API 而不是 Web 服务。这将允许您使用 REST 服务。

方法 2:如果您坚持使用网络服务,那么以下链接将非常有帮助。 https://www.one-tab.com/page/IjhbYbayRlWka-8ruNI87w

在我的 AJAX 成功从 Web 服务返回 JSON 之后。下一个问题是将数据绑定到网格插件。这非常简单明了。找到你要使用的方法的demo,将整个东西复制粘贴到AJAX请求的成功回调函数中。您甚至可以通过在 AJAX 请求的成功回调函数内部调用用户定义的函数来传递您收到的数据。

有时您在使用 AJAX 请求使用 Web 服务时可能会遇到一个问题,即“在序列化或反序列化过程中出现错误。超出了最大 JSON 长度属性”。如果您确实遇到这种情况,请尝试将 javascriptSerializer 对象初始化为 maxInt 值。

如果您使用的是 Newtonsoft .JSON,请检查您的数据是否使用常规 javascriptSerializer 类进行序列化。我之所以这么说是因为 AJAX 请求使用 javascriptSerializer 和 Newtonsoft .JSON 序列化数据往往会忽略循环引用错误。因此,当您的 Web 服务实际上遇到循环引用错误时,Ajax 函数可能会抛出“在序列化或反序列化期间出现错误。超出最大 JSON 长度属性”错误。如果是这种情况,请考虑更改您正在使用的 SP 或查询。

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多