簡體   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