如何在 jQuery 中调用 C# 方法?

2024-01-26

我正在使用一个图表,它应该从 C# 获取输入来绘制图表。我使用 JSON 将值从 C# 返回到 jQuery。无论如何,这对我没有帮助,我做错了什么?

这是我的 aspx 代码:

<script type="text/javascript">
    $(document).ready(function () {
        var source = {};

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: "Default.aspx/getall",
            contentType: 'application/json; charset=utf-8',
            cache: false,
            success: function (response) {

                source = $.parseJSON(response.d);

            },
            error: function (err) {
                alert('Error');
            }
        });
</script>

这是我的 C# 代码:

public class sampledata
{
    public string Day { get; set; }
    public int Keith { get; set; }
    public int Erica { get; set; }
    public int George { get; set; }
}

public partial class _Default : System.Web.UI.Page 
{
    List<sampledata> s = new List<sampledata>();

    protected void Page_Load(object sender, EventArgs e)
    {
        s.Add(new sampledata { Day = "monday", Keith = 20, Erica = 15, George = 25 });
        s.Add(new sampledata { Day = "tuesday", Keith = 25, Erica = 20, George = 35 });

        Session["data"] = s;                  
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static List<sampledata> getall()
    {
        List<sampledata> data = (List<sampledata>)HttpContext.Current.Session["data"];
        return data;
    }
}

我测试了你的代码,一切似乎都很好,除了我将列表序列化为字符串并返回。

$(window).load(function () {
    $.ajax({
        type: "POST",
        url: "PageMethodTest.aspx/getall",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: fnsuccesscallback,
        error: fnerrorcallback
    });
});

function btnclick() {}

function fnsuccesscallback(data) {
    alert(data.d);

}

function fnerrorcallback(result) {
    alert(result.statusText);
}

服务器端代码:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static String getall()
{
    List<sampledata> data = (List<sampledata>)HttpContext.Current.Session["data"];
    JavaScriptSerializer js = new JavaScriptSerializer();

    return js.Serialize(data);
    //return data;
}

结果是:

您可以改进使用输出作为图表源。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 jQuery 中调用 C# 方法? 的相关文章