繁体   English   中英

尝试使用 C# web 方法(ASP .NET)将来自 SQL 服务器的数据绑定到使用 ZF590B4CZDC23 编码的网格中

[英]Trying to bind data from SQL Server using a C# web method(ASP .NET) to a grid coded using jQuery

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

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

我已经使用上面链接中的源代码来构建网格,但是当我运行程序时,数据没有显示出来。 I am sure that the issue lies in the jQuery because I have run my web service separately and it connects to SQL Server and displays the output in the form of a JSON array.

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

  1. 实践验证项目 - 包含 3.aspx c# web forms。 一个用于主页,另一个用于配方表格,第三个用于员工表格。
  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 项目:该项目包含一个 c# class 文件,该文件负责与 SQL 服务器交互。 我在下面的这个文件中附加了代码。
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. web 服务已加载到我的本地浏览器上

  2. 调用员工 web 方法后的 output

  3. 调用配方 web 方法后的 output

现在我相信所有阅读这篇文章的人都会对我正在尝试做的事情有一个更清晰的想法。 所以现在我将附上employee.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>

最后附上我得到的output的截图。

员工record.aspx页面的Output: 在此处输入图像描述

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

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

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

我遇到的下一个问题很棘手,我花了很长时间才弄清楚。 Irrespective of serializing the data coming from SQL into JSON, the data that actually gets sent back from the web service is XML. 这是因为 web 服务使用 SOAP,因此默认情况下数据传输的方法是 XML。 如果您运行 web 服务并观察数据,您将看到带有 XML 包装器的 JSON 字符串。 If you open Chrome dev tools and look at the content-type, you would see that its returning XML and no matter what you do, you cannot stop a web service from returning XML through an AJAX 'GET' request. 那么你如何解决这个问题呢? 两种方式:

方法一:使用 Web API 代替 Web 服务。 这将允许您使用 REST 服务。

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

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

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

如果您使用 Newtonsoft.JSON,请检查您的数据是否使用常规 javascriptSerializer class 进行序列化。 我之所以这么说是因为AJAX 请求使用javascriptSerializer 和Newtonsoft 序列化数据。JSON 往往会忽略循环引用错误。 As a result, the Ajax function might throw a "there was an error during serializing or deserializing. Maximum JSON length property exceeded" error when in actuality your web service is running into a circular reference error. 如果是这种情况,请考虑对您正在使用的 SP 或查询进行更改。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM