简体   繁体   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

I hope the title of my question is descriptive and helpful for you to understand the issue that I am facing.我希望我的问题的标题是描述性的,有助于您理解我面临的问题。 I am new to programming, and I am aware that the issue I am facing is something that only a beginner would have issues with.我是编程新手,我知道我面临的问题是只有初学者才会遇到的问题。 Please do help me out.请帮帮我。 Please bear with me as this is quite a long description.请耐心等待,因为这是一个很长的描述。 I am aware that most of you who are a part of this community are very experienced programmers and wouldn't require such detailed methodology but it isn't my intention to waste your time and I believe that by giving such a detailed description, you would be able to help me better.我知道在这个社区中的大多数人都是非常有经验的程序员,不需要如此详细的方法,但我无意浪费你的时间,我相信通过提供如此详细的描述,你会能够更好地帮助我。 Now about the issue, I am trying to build a grid using jQuery:现在关于这个问题,我正在尝试使用 jQuery 构建一个网格:

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

I have used the source code from the link above to build the gird, but when I run the program, the data doesn't get displayed.我已经使用上面链接中的源代码来构建网格,但是当我运行程序时,数据没有显示出来。 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. 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.

I have broken the solution into three projects on Visual Studio 2019:我在 Visual Studio 2019 上将解决方案分为三个项目:

  1. PracticeValidation project - contains 3.aspx c# web forms.实践验证项目 - 包含 3.aspx c# web forms。 One for the homepage, another for the recipe form and a third for the employee form.一个用于主页,另一个用于配方表格,第三个用于员工表格。
  2. WebServicesFunctionality project - Contains one.asmx Webservice file which holds 2 web methods(one for the recipe form, the other for the employee form) to serialise the data coming in the form of a list into a JSON array. WebServicesFunctionality 项目 - 包含一个.asmx Webservice 文件,其中包含 2 个 web 方法(一个用于配方表单,另一个用于员工表单)以将列表形式的数据序列化为 JSON 数组。 Please find the code for the web service attached below.请在下面找到 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 project: This project holds a c# class file which is responsible for interacting with SQL Server. FormGeneratorClass 项目:该项目包含一个 c# class 文件,该文件负责与 SQL 服务器交互。 I am attaching the code inside this file below.我在下面的这个文件中附加了代码。
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;
        }
    }
}

I will set the WebServicesFunctionality project(pt.2) as the startup project and take a screenshot of the result I get for your reference我将WebServicesFunctionality项目(pt.2)设置为启动项目,并将我得到的结果截图供您参考

  1. The web service is loaded on my local browser web 服务已加载到我的本地浏览器上

  2. The output after the employee web method gets invoked调用员工 web 方法后的 output

  3. The output after the recipe web method gets invoked调用配方 web 方法后的 output

Now I'm sure all those reading this post will have a clearer idea about what I'm trying to do.现在我相信所有阅读这篇文章的人都会对我正在尝试做的事情有一个更清晰的想法。 So now I'll attach the code for employee.aspx page.所以现在我将附上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>

I will finally attach the screenshot of the output that I get.最后附上我得到的output的截图。

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

Thank you to all those who have read the whole post and stay safe!感谢所有阅读整篇文章并保持安全的人!

I figured out where I was going wrong.我知道我哪里错了。 There were a lot of reasons why the data wasn't getting bound to the grid the way I wanted.数据没有按照我想要的方式绑定到网格有很多原因。 I hope this is helpful for anybody else with the same issue.我希望这对其他有同样问题的人有所帮助。

The first problem you need to solve if you're creating a solution the way I did is that you need to create a proxy web service that gets the data from the web service.如果您按照我的方式创建解决方案,您需要解决的第一个问题是您需要创建一个代理 web 服务,该服务从 web 服务获取数据。 This is because, the web service project and the web form project run on a different port.这是因为,web 服务项目和 web 表单项目在不同的端口上运行。 So, even if everything is right, you would get a 404 error when making an AJAX request.因此,即使一切正常,您在发出 AJAX 请求时也会收到 404 错误。 So create a web service proxy from the web form project or else just ditch the idea of creating a separate web service project.因此,从 web 表单项目创建一个 web 服务代理,否则就放弃创建单独的 web 服务项目的想法。

The next problem I ran into was a doozy and took me a really long time to figure out.我遇到的下一个问题很棘手,我花了很长时间才弄清楚。 Irrespective of serializing the data coming from SQL into JSON, the data that actually gets sent back from the web service is XML. Irrespective of serializing the data coming from SQL into JSON, the data that actually gets sent back from the web service is XML. This is because web services use SOAP and hence by default the method of data transfer is XML.这是因为 web 服务使用 SOAP,因此默认情况下数据传输的方法是 XML。 If you run your web service and observe the data, you will see a JSON string with an XML wrapper.如果您运行 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. 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. So how do you solve the problem?那么你如何解决这个问题呢? Two ways:两种方式:

Method 1: Use a Web API instead of a Web service.方法一:使用 Web API 代替 Web 服务。 This will allow you to use REST services.这将允许您使用 REST 服务。

Method 2: If you're adamant about using a web service, then the following link will be super helpful.方法 2:如果您坚持使用 web 服务,那么以下链接将非常有帮助。 https://www.one-tab.com/page/IjhbYbayRlWka-8ruNI87w https://www.one-tab.com/page/IjhbYbayRlWka-8ruNI87w

After I got my AJAX returning JSON from a web service successfully.在我的 AJAX 从 web 服务成功返回 JSON 之后。 The next issue was getting the data bound to the grid plug in. This is pretty simple and straightforward.下一个问题是将数据绑定到网格插件。这非常简单明了。 Find the demo of the method you want to use and copy paste the entire thing into the success call back function of the AJAX request.找到您要使用的方法的演示并将整个内容复制粘贴到 AJAX 请求的成功回调 function 中。 You could even pass the data you are receiving by calling a user defined function INSIDE the success call back function of the AJAX request.您甚至可以通过在 AJAX 请求的成功回调 function 中调用用户定义的 function 来传递您收到的数据。

Sometimes you might run into an issue when consuming a web service using an AJAX request which says that "there was an error during the serializing or deserializing. Maximum JSON length property exceeded".有时您可能会在使用 AJAX 请求使用 web 服务时遇到问题,该请求说“在序列化或反序列化过程中出现错误。超出了最大 Z0ECD11C1D7A287401D148A23BBD7A2F8 长度属性”。 If you do face this try initializing the javascriptSerializer object to a maxInt value.如果您确实遇到这种情况,请尝试将 javascriptSerializer object 初始化为 maxInt 值。

If you are using Newtonsoft.JSON, then please check to see if your data gets serialized using the regular javascriptSerializer class.如果您使用 Newtonsoft.JSON,请检查您的数据是否使用常规 javascriptSerializer class 进行序列化。 The reason why I say this is because AJAX requests serialize data using javascriptSerializer and Newtonsoft.JSON tends to overlook circular reference errors.我之所以这么说是因为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. 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. Consider making changes to the SP or query that you are using if this is the case.如果是这种情况,请考虑对您正在使用的 SP 或查询进行更改。

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

相关问题 如何在ASP.NET C#中使用jquery绑定ul标签 - How to Bind ul tag using jquery in asp.net C# 在ASP.net和C#中使用jQuery - Using jquery with ASP.net and C# 尝试使用C#asp.net Web表单使epaper动态化 - Trying to make epaper dynamic using C# asp.net web form 如何使用c#从asp.net中的数据库绑定图像? - how to bind image from database in asp.net using c#? 如何使用asp.net C#中的Ajax和Web服务使用数据库中的数据填充动态创建的下拉列表 - how fill the dynamically created dropdownlist with data from database using ajax and web service in asp.net c# 使用Jquery对Asp.net Web方法进行Ajax调用 - Ajax call to Asp.net Web Method using Jquery 如何创建动态生成的按钮,以在ASP.Net C#中使用javascript调用服务器端方法 - how to create dynamicly generated button that call server side method in using javascript in ASP.Net c# 使用ASP.Net C#中的JavaScript将Calendar对象传递到服务器端方法 - Pass Calendar object to a server side method using JavaScript in ASP.Net C# 如何使用c#将服务器端处理的数据从代码隐藏添加到asp.net中.aspx页面中的javascript - How to add server-side processed data from code-behind to javascript in .aspx page in asp.net using c# 在ASP.NET/C#中检查复选框服务器控件时隐藏文本框-使用Jquery或Javascript - Hide a TextBox on checking a checkbox server control in ASP.NET/C# - using Jquery or Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM