Visualisasikan Data dengan Berkesan: Tambah Grid dan Carta dalam Senarai Medan Pangsi JavaScript

王林
Lepaskan: 2024-09-10 11:04:53
asal
1012 orang telah melayarinya

TL;DR:Mari lihat cara menambah Grid dan Carta pada Senarai Medan Jadual Pangsi JavaScript dengan enjin sebelah pelayan. Kami akan meliputi penyediaan API Web, menyambungkan Senarai Medan Pangsi kepada API dan menghantar data input untuk memaparkan Grid dan Carta. Blog ini juga menunjukkan cara menapis dan mengemas kini komponen secara dinamik berdasarkan interaksi pengguna untuk visualisasi data masa nyata.

Senarai Medan Pangsi JavaScript ialah komponen berkuasa yang berfungsi serupa dengan Microsoft Excel. Ia membolehkan anda menambah atau mengalih keluar medan dan menyusunnya semula merentas paksi yang berbeza, seperti lajur, baris, nilai dan penapis. Pilihan isih dan penapis juga boleh digunakan secara dinamik pada masa jalan.

Dalam blog ini, kami akan melihat langkah terperinci untuk mencipta Grid dan Carta menggunakan komponen Senarai Medan Jadual Pangsi JavaScript dengan enjin bahagian pelayan kami. Di sini, kami tidak akan menggunakan ciri grid dan carta terbina dalam dalam Jadual Pangsi. Sebaliknya, kami akan menambah komponen Syncfusion JavaScript DataGrid dan Carts untuk menggambarkan data dengan berkesan.

Untuk berbuat demikian, kita perlu mencipta Senarai Medan menggunakan enjin sebelah pelayan.

Apakah enjin sebelah pelayan?

Enjin sebelah pelayan boleh menyambung terus ke sumber data anda, mengumpul data input mentah dan secara berkala melakukan semua pengiraan berorientasikan pangsi secara dalaman berdasarkan laporan yang disediakan oleh Jadual Pangsi JavaScript melalui interaksi UI. Ia kemudian menghantar hanya data agregat untuk Jadual Pangsi atau Carta Pangsi ke bahagian pelanggan (penyemak imbas).

Nota:Untuk butiran lanjut, rujuk pada melaksanakan enjin bahagian pelayan dalam dokumentasi Jadual Pangsi JavaScript.

Langkah untuk membina Senarai Medan Pangsi dalam apl Teras ASP.NET

Ikuti langkah ini untuk mencipta Senarai Medan Pangsi dalam apl Teras ASP.NET:

Langkah 1: Mencipta pengawal WebAPI

Mulakan dengan membuka Visual Studio dan mencipta apl Teras ASP.NET kosong. Rujuk imej berikut.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Kemudian, cipta pengawal WebAPI kosong dan namakannya sebagai PivotController. Rujuk imej berikut.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Langkah 2: Pasang pakej Syncfusion.Pivot.Engine NuGet

Untuk menggunakan enjin bahagian pelayan, pasang pakej Syncfusion.Pivot.Engine NuGet daripada Galeri NuGet, seperti yang ditunjukkan dalam imej berikut.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Langkah 3: Mengkonfigurasi pengawal API Web

Untuk memaparkan Senarai Medan Pangsi, tambahkan kod berikut pada fail PivotController.cs dan Program.cspada bahagian pelayan.

Dalam PivotController, kami akan menetapkan data kosong kepada PivotEngine.Dataharta dalam kaedah GetPivotValues, yang mengandungi medan yang akan dipaparkan dalam Senarai Medan Pangsi. Kami boleh menjana medan menggunakan Koleksi, JSON, CSV, Jadual Data,atau Dinamiksumber data. Di sini, kami telah menggunakan ExpandoObject (Dinamik) untuk menetapkan data.

[PivotController.cs]

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Syncfusion.Pivot.Engine;
using System.Diagnostics.Metrics;
using System.Dynamic;

namespace PivotController.Controllers
{
    [Route("api/[controller]")]
    public class PivotController : Controller
    {
        private PivotEngine<ExpandoObject> PivotEngine = new PivotEngine<ExpandoObject>();

        [Route("/api/pivot/post")]
        [HttpPost]
        public async Task<object> Post([FromBody] object args)
        {
            FetchData param = JsonConvert.DeserializeObject<FetchData>(args.ToString());
            if (param.Action == "fetchFieldMembers")
            {
                return await GetMembers(param);
            }
            else
            {
                return await GetPivotValues(param);
            }
        }

        private async Task<object> GetMembers(FetchData param)
        {
            Dictionary<string, object> returnValue = new Dictionary<string, object>();
            if (param.MemberName == "Year")
            {
                returnValue["memberName"] = param.MemberName;
                Dictionary<string, Members> result = new Dictionary<string, Members>();
                result.Add("FY 2005", new Members()
                {
                    Caption = "FY 2005",
                    Name = "FY 2005",
                    IsSelected = true
                });
                result.Add("FY 2006", new Members()
                {
                    Caption = "FY 2006",
                    Name = "FY 2006",
                    IsSelected = true
                });
                result.Add("FY 2007", new Members()
                {
                    Caption = "FY 2007",
                    Name = "FY 2007",
                    IsSelected = false
                });
                result.Add("FY 2008", new Members()
                {
                    Caption = "FY 2008",
                    Name = "FY 2008",
                    IsSelected = false
                });
                returnValue["members"] = JsonConvert.SerializeObject(result);
            }
            return returnValue;
        }

        private async Task<object> GetPivotValues(FetchData param)
        {
            List<ExpandoObject> listData = new List<ExpandoObject>();
            dynamic d = new ExpandoObject();
            d.ProductID = "";
            d.Year = "";
            d.Country = "";
            d.Product = "";
            d.Price = 0;
            d.Sold = 0;
            listData.Add(d);
            PivotEngine.Data = listData;
            EngineProperties engine = await PivotEngine.GetEngine(param);
            Dictionary<string, object> result = PivotEngine.GetSerializedPivotValues();
            result["pivotCount"] = "";
            result["pivotValue"] = "";
            result["data"] = new PivotViewData().GetVirtualData(1000, param);
            return result;
        }

        public class PivotViewData
        {
            public string ProductID { get; set; }
            public string Country { get; set; }
            public string Product { get; set; }
            public double Sold { get; set; }
            public double Price { get; set; }
            public string Year { get; set; }

            public List<PivotViewData> GetVirtualData(int count, FetchData param)
            {
                List<PivotViewData> VirtualData = new List<PivotViewData>();

                for (int i = 1; i <= count; i++)
                {
                    PivotViewData p = new PivotViewData
                    {
                        ProductID = "PRO-" + (count + i),
                        Year = param.Action == "onFilter" ? param.FilterItem.Items[new Random().Next(param.FilterItem.Items.Length)] : (new string[] { "FY 2015", "FY 2016", "FY 2017", "FY 2018", "FY 2019" })[new Random().Next(5)],
                        Country = (new string[] { "Canada", "France", "Australia", "Germany", "France" })[new Random().Next(5)],
                        Product = (new string[] { "Car", "Van", "Bike", "Flight", "Bus" })[new Random().Next(5)],
                        Price = (3.4 * i) + 500,
                        Sold = (i * 15) + 10
                    };
                    VirtualData.Add(p);
                }
                return VirtualData;
            }
        }
    }
}
Salin selepas log masuk

[Program.cs]

var builder = WebApplication.CreateBuilder(args);
var CustomOrigins = "_customOrigins";

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddCors(options =>
{
    options.AddPolicy(CustomOrigins,
    builder =>
    {
        builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
    });
});

var app = builder.Build();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();
app.UseCors(CustomOrigins);
app.Run();
Salin selepas log masuk

Setelah kod dikemas kini, jalankan apl dalam IIS. Ia boleh diakses di https://localhost:44372/api/pivot/post.

Langkah 4: Sambungkan Senarai Medan Pangsi JavaScript dengan pengawal WebAPI

Untuk menyambungkan enjin bahagian pelayan kepada Senarai Medan Pangsi JavaScript, buat Medan Pangsi JavaScript kendiri yang mudah. Petakan URL API Web yang dihoskan, https://localhost:44372/api/pivot/post, ke Jadual Pangsi dalam index.jsfail menggunakan sifat url di bawah dataSourceSettings.

Rujuk contoh kod berikut.

[pivot.js]

var fieldlistObj = new ej.pivotview.PivotFieldList({
    dataSourceSettings: {
       // Here, we need to use the service URL.
        url: 'https://localhost:44372/api/pivot/post',
        mode: 'Server',
        type: 'JSON',
        allowMemberFilter: true,
        rows: [{ name: 'Year' }],
        values: [{ name: 'Sold', caption: 'Units Sold' }],
        fieldMapping: [
            { name: 'Sold', type: 'Sum' },
            { name: 'Price', type: 'Sum' },
        ],
    },
    renderMode: 'Fixed',
});
fieldlistObj.appendTo('#PivotFieldList');
Salin selepas log masuk

Setelah kod di atas dilaksanakan, Senarai Medan Pangsi akan muncul, seperti yang ditunjukkan dalam imej berikut.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Sambungkan Senarai Medan Pangsi JavaScript dengan pengawal WebAPI

Langkah 5: Menghantar data input ke Senarai Medan Pangsi JavaScript

Berdasarkan laporan yang kami ikat dalam Senarai Medan Pangsi JavaScript, kami boleh mendapatkan semula data daripada pangkalan data dan mengembalikannya kepada pelanggan.

For example, we used the PivotViewDataclass to create a sample list (Collection) data source and returned it to the client through the GetPivotValues()method.

The data can be retrieved by calling the Pivot Field List’s afterServiceInvoke event. Then, the Grid and Chartcomponents can be rendered with the data obtained from that event.

Refer to the following code example to render the DataGrid and Charts components based on the input data in the JavaScript Pivot Field List.

[pivot.js]

var fieldlistObj = new ej.pivotview.PivotFieldList({
    dataSourceSettings: {
        url: 'https://localhost:44372/api/pivot/post',
        mode: 'Server',
        type: 'JSON',
        allowMemberFilter: true,
        rows: [{ name: 'Year' }],
        values: [{ name: 'Sold', caption: 'Units Sold' }],
        fieldMapping: [
            { name: 'Sold', type: 'Sum' },
            { name: 'Price', type: 'Sum' },
        ],
    },
    renderMode: 'Fixed',
    afterServiceInvoke: function (args) {
        if (args.action != "fetchFieldMembers") {
            data = JSON.parse(args.response).data;
            grid.dataSource = data;
            grid.columns = getColumns();
            chart.series[0].dataSource = data;
        }
    }
});
fieldlistObj.appendTo('#PivotFieldList');

var grid = new ej.grids.Grid({
    allowSelection: true,
    allowFiltering: true,
    allowSorting: true,
    filterSettings: { type: 'Menu' },
    selectionSettings: {
        persistSelection: true,
        type: 'Multiple',
        checkboxOnly: true,
    },
    enableHover: false,
    enableHeaderFocus: true,
    height: 250
});
grid.appendTo('#Grid');

var chart = new ej.charts.Chart({
    primaryXAxis: {
        valueType: 'Category',
        labelRotation: 90,
        zoomFactor: 0.1
    },
    chartArea: { border: { width: 0 } },
    primaryYAxis: {
        title: 'Units Sold'
    },
    series: [
        {
            type: 'Column',
            xName: 'productID',
            width: 2,
            yName: 'sold',
            name: 'Sales',
        },
    ],
    zoomSettings: {
        enableScrollbar: true
    },
    title: 'Sales Analysis',
    width: '100%',
    tooltip: { enable: true, shared: true },
    legendSettings: { enableHighlight: true },
});
chart.appendTo('#Chart');

function getColumns() {
    var report = {};
    report[0] = fieldlistObj.dataSourceSettings.rows;
    report[1] = fieldlistObj.dataSourceSettings.columns;
    report[2] = fieldlistObj.dataSourceSettings.values;
    report[3] = fieldlistObj.dataSourceSettings.filters;
    var pos = 0;
    var columns = [];
    while (pos < 4) {
        if (report[pos]) {
            for (var cnt = 0; cnt < report[pos].length; cnt++) {
                var field = report[pos][cnt];
                var column = {
                    field: field.name,
                    headerText: field.caption ? field.caption : field.name,
                    width: 150,
                    textAlign: 'Center',
                };
                columns.push(column);
            }
        }
        pos++;
    }
    return columns;
}
Salin selepas log masuk

Refer to the following output image.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Creating the Grid and Chart based on the input provided in the JavaScript Pivot Field List

How does the server-side engine work?

Every action in the JavaScript Pivot Field List, such as adding or removing fields, rearranging them across different axes, including columns, rows, values, and filters, and dynamically sorting and filtering options, sends an updated report to the server at runtime. Based on that, we can retrieve data from the database and return it to the client side, enabling us to refresh both Grid and Chart components with the new data.

Updating the Grid and Chart with filtered data

Let’s walk through how to update the Grid and Chart by filtering the field list. When we click the filter icon in a field to which we’ve bound the data source, the server ( PivotController) receives a request with the action name fetchFieldMembersand the name of the specified field. Based on that, we can use the GetMemebers()method to pass the members to the filter dialog.

Refer to the following code example to know how the server-side engine handles this filtering process.

[PivotController.cs]

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Syncfusion.Pivot.Engine;
using System.Diagnostics.Metrics;
using System.Dynamic;

namespace PivotController.Controllers
{
    [Route("api/[controller]")]
    public class PivotController : Controller
    {
        private PivotEngine<ExpandoObject> PivotEngine = new PivotEngine<ExpandoObject>();

        [Route("/api/pivot/post")]
        [HttpPost]
        public async Task<object> Post([FromBody] object args)
        {
            FetchData param = JsonConvert.DeserializeObject<FetchData>(args.ToString());
            if (param.Action == "fetchFieldMembers")
            {
                return await GetMembers(param);
            }
            else
            {
                return await GetPivotValues(param);
            }
        }

        private async Task<object> GetMembers(FetchData param)
        {
            Dictionary<string, object> returnValue = new Dictionary<string, object>();
            if (param.MemberName == "Year")
            {
                returnValue["memberName"] = param.MemberName;
                Dictionary<string, Members> result = new Dictionary<string, Members>();
                result.Add("FY 2015", new Members()
                {
                    Caption = "FY 2015",
                    Name = "FY 2015",
                    IsSelected = true
                });
                result.Add("FY 2016", new Members()
                {
                    Caption = "FY 2016",
                    Name = "FY 2016",
                    IsSelected = true
                });
                result.Add("FY 2017", new Members()
                {
                    Caption = "FY 2017",
                    Name = "FY 2017",
                    IsSelected = true
                });
                result.Add("FY 2018", new Members()
                {
                    Caption = "FY 2018",
                    Name = "FY 2018",
                    IsSelected = true
                });
                returnValue["members"] = JsonConvert.SerializeObject(result);
            }
            return returnValue;
        }
}
Salin selepas log masuk

After executing the above code, the members will be displayed in the filter dialog, as shown in the following image.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Displaying filter members in the JavaScript Pivot Field List

The members can then be filtered using the filter dialog. The filtered members are sent to the server along with their field names. Based on the filtered members, we can fetch data from the database and return it to the client to refresh the Grid and Chart components.

For example, we have filtered the Yearfield, as shown in the following image.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Filtering data via the filter dialog in JavaScript Pivot Field List

The filtered members FY 2015and FY 2018will be sent to the server, along with the field name Year. So, we can use that information to filter and retrieve data from the database via the afterServiceInvokeevent, which we can then return to the client to refresh the Grid and Chart components.

Once the filtered data from the database has been assigned to them, the grid and chart will look like this.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Updating the Grid and Chart in the JavaScript Pivot Field List with the filtered data

GitHub reference

For more details, check out the Adding Grids and Charts in JavaScript Pivot Field List GitHub demo.

Conclusion

Thanks for reading! In this blog, we’ve seen how to add the DataGrid and Charts component to the JavaScript Pivot Table’s Field List to effectively visualize data. This approach can also be used to integrate Syncfusion’s other JavaScript data visualization components. Follow the steps outlined in this blog, and let us know your thoughts in the comments!

For existing customers, the latest version of Essential Studio can be downloaded from the License and Downloads page. If you are new to Syncfusion, try our 30-day free trial to check out the available features.

For any questions, you can contact us through our support forum, support portal, or feedback portal. We are always happy to assist you!

Blogs connexes

  • Créez facilement des diagrammes de planificateur d'étage interactifs à l'aide de la bibliothèque de diagrammes JavaScript
  • Synchronisez sans effort les contrôles JavaScript à l'aide de DataManager
  • Optimiser la productivité : intégrer Salesforce avec JavaScript Scheduler
  • Optimiser la gestion de la mémoire dans le tableau croisé dynamique JavaScript : bonnes pratiques et astuces

Atas ialah kandungan terperinci Visualisasikan Data dengan Berkesan: Tambah Grid dan Carta dalam Senarai Medan Pangsi JavaScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!