javascript - 在 javascript 中更新 c# 变量有问题吗?

标签 javascript c# highcharts

我正在学习使用 javascript 和 c#。所以,我使用 highcharts 来绘制一些我从 c# 传递到 javascript 的数据。现在,我想手动更新 c# 中的变量以查看 javascript 中值的变化,但由于某种原因,变量不会更新。我做错了什么?到目前为止,这是我尝试过的。我更新了变量“merchantname”,但由于某种原因,我的前端没有任何反应。

最佳答案

您的页面没有按照您认为应该更新的方式进行更新的原因有两个:

  • 虽然你使用ajax向你的webservice发送请求,但是你真正的数据服务端点有一个void return,这意味着它不返回任何东西,这不是很实用

  • 您的柜台服务正在做一些更新,并返回一个数字,但仅此而已

所以在 C# 端,您应该返回一个类型化对象,以便您可以在 javascript 响应中使用它,比方说,您添加一个名为 FruitItem 的类

public class FruitItem {
    public string Name { get; set; }
    public int Failed { get; set; }
    public int Succeeded { get; set; }
    public int Service { get; set; }

    public FruitItem(string name, int failed, int succeeded, int service) {
        Name = name;
        Failed = failed;
        Succeeded = succeeded;
        Service = service;
    }
}

这样,与使用断开连接的数组相比,您可以使数据更具凝聚力。

现在必须将此数据传输回您的客户端,因此在您当前的设置中,我们需要更改 calctransctl 方法,以便它返回此类数据。如果我们按以下方式更改它,我们可以返回一个 FruitItems 数组

[WebMethod]
public static FruitItem[] calctranscs()
{
    return new FruitItem[] {
        new FruitItem("Strawberry", 100, 200, 400),
        new FruitItem("Apples", 200, 100, 400),
        new FruitItem("Pineapple", 300, 200, 400),
        new FruitItem("Mango", 100, 200, 400)
    };
}

或者(如果您希望继续使用断开连接的数组),您也可以返回一个包含断开连接数组的匿名对象,如下所示:

[WebMethod]
public static object calctranscs() {
    return new { 
        merchant_names = new string[] { "Strawberry", "Apples", "Pineapple", "Mango" },
        failures = new int[] {100, 200, 300, 100},
        succeeded = new int[] {200, 100, 200, 200},
        service = new int[] {400, 400, 400, 400}
    };
}

这将返回一个包含您的数据的匿名对象(目前,答案的其余部分将包含带有对象的版本)

接下来我们必须改变的是在你的 ajax 回调中处理现在接收到的数据,你的 calcfunc 方法现在必须处理它得到的响应

function callfunc() {
    $.ajax({
        type: "POST",
        url: "getcharts.aspx/calctranscs",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            klm( result.d );
            abc( result.d );
            // please note, I removed the setInterval here, we can do it at initializing time
        },
        error: function (result) {
            alert(result.responseText);
        }
    });
}

我们现在知道你的 result.d 包含一个对象数组,包含以下属性

  • 名称:字符串
  • 失败:编号
  • 成功:number
  • 服务:号码

因此,要将这些映射到图表函数的预期输入,您可以像这样更改 klm 函数(以及以类似方式更改 abc 函数)

function mapData( data, property ) {
  return data.map( function( item ) {
    return item[property];
  } );
}

function klm( data ) {
    var merchantname = mapData( data, "Name" );
    var servicevalue = mapData( data, "Service" );
    var failedvalue = mapData( data, "Failed" );
    var successvalue = mapData( data, "Succeeded" );
    // the rest of your code is unchanged
}

此函数将接收您的数据,然后根据属性创建数组,如果您返回包含数组的匿名对象,您会更容易一些,例如

function klm( data ) {
    var merchantname = data.merchant_names;
    var servicevalue = data.service;
    var failedvalue = data.failures;
    var successvalue = data.succeeded;
    // the rest of your code is unchanged
}

我在您的 .aspx 页面中所做的额外更改是在加载所有 javascript 文件后仅加载完整数据,因此这将包装您的整个 javascript 部分

$(function() {
    function callfunc() {
        $.ajax({
            type: "POST",
            url: "getcharts.aspx/calctranscs",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                klm( result.d );
                abc( result.d );
            },
            error: function (result) {
                alert(result.responseText);
            }
        });
    }

    function Counter() {
        $.ajax({
            type: "POST",
            url: "getcharts.aspx/Counter",
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (result) {
                console.log(result.d);
                callfunc();
            },
            error: function (result) {
                alert(result.responseText);
            }
        });

    }

    function mapData( data, property ) {
        return data.map( function( item ) {
            return item[property];
        } );
    }

    function klm( data ) {
        var merchantname = mapData( data, "Name" );
        var servicevalue = mapData( data, "Service" );
        var failedvalue = mapData( data, "Failed" );
        var successvalue = mapData( data, "Succeeded" );

        Highcharts.chart('container1', {
            chart: {
                type: 'column'
            },
            title: {
                text: 'Stacked column chart'
            },
            xAxis: {
                categories: merchantname
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Transaction Status'
                },
                stackLabels: {
                    enabled: true,
                    style: {
                        fontWeight: 'bold',
                        color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                    }
                }
            },
            legend: {
                align: 'right',
                x: -30,
                verticalAlign: 'top',
                y: 25,
                floating: true,
                backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
                borderColor: '#CCC',
                borderWidth: 1,
                shadow: false
            },
            tooltip: {
                headerFormat: '<b>{point.x}</b><br/>',
                pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
            },
            plotOptions: {
                column: {
                    stacking: 'normal',
                    dataLabels: {
                        enabled: true,
                        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
                    }
                }
            },
            series: [{
                name: 'Service',
                data: servicevalue
            }, {
                name: 'Failure',
                data: failedvalue
            }, {
                name: 'Success',
                data: successvalue
            }]
        });

    }

    function abc( data ) {
        var merchantname = mapData( data, "Name" );
        var servicevalue = mapData( data, "Service" );
        var failedvalue = mapData( data, "Failed" );
        var successvalue = mapData( data, "Succeeded" );

        Highcharts.chart('container3', {
            chart: {
                type: 'column'
            },
            title: {
                text: 'Stacked column chart'
            },
            xAxis: {
                //  categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
                categories: merchantname
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Total fruit consumption'
                },
                stackLabels: {
                    enabled: true,
                    style: {
                        fontWeight: 'bold',
                        color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                    }
                }
            },
            legend: {
                align: 'right',
                x: -30,
                verticalAlign: 'top',
                y: 25,
                floating: true,
                backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
                borderColor: '#CCC',
                borderWidth: 1,
                shadow: false
            },
            tooltip: {
                headerFormat: '<b>{point.x}</b><br/>',
                pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
            },
            plotOptions: {
                column: {
                    stacking: 'normal',
                    dataLabels: {
                        enabled: true,
                        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
                    }
                }
            },
            series: [{
                name: 'Service',
                data: servicevalue
            }, {
                name: 'Failure',
                data: failedvalue
            }, {
                name: 'Success',
                data: successvalue
            }]
        });
    }

    callfunc();
    setInterval(Counter, 30000);
});

显着的变化是包装 $(function() {/*... your code ...*/}) 它将等待所有 javascript 代码被加载,并且 setInterval已从回调移动到第一个被调用的函数之一(在 callfunc 之后)。

每次触发间隔并成功时,都会触发对 callfunc 的新调用,并且您的数据可能会被重绘

(请注意,最后一段代码也是使用 FruitItem 文本的工作代码,而不是匿名对象)

关于javascript - 在 javascript 中更新 c# 变量有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41415263/

相关文章:

javascript - (ReactAssign firebase snapshot 到函数外部的变量

php - Highcharts——从 mysql 获取类别

Highcharts - 更改图例索引顺序

c# - 添加项目时在 ConcurrentDictionary<TKey, TValue> 上调用 ToList()

c# - 从 DGV 中删除——索引 [x] 没有值

javascript - CSS/JavaScript : hidden div does not take full width after being shown

javascript - 揭开文字周围的括号的神秘面纱

javascript - JSONP回调乱序

javascript - YouTube API getRating "none"或 "unspecified"

c# - 面板滚动后,面板内的 DataGridView 跳转到列表的开头