首页 > 解决方案 > 非静态字段、方法或属性“System.Web.UI.Control.Context.get”需要对象引用

问题描述

我在编码中遇到了这个错误。下面给出了我的代码,我需要将值传递给 jquery 以显示数据。这个错误“ An object reference is required for the non-static field, method, or property 'System.Web.UI.Control.Context.get'”是什么?

[WebMethod]
public static string GetData()
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["tempsConnectionString"].ConnectionString);
    List<Glassrecord> glass = new List<Glassrecord>();
    SqlCommand cmd = new SqlCommand("Select Prod_date,GreenTime,YellowTime  from CrystalProdTracker  ", con);
    con.Open();

    SqlDataReader sdr = cmd.ExecuteReader();

    while (sdr.Read())
    {
        Glassrecord glassrec = new Glassrecord();
        glassrec.Date = sdr["Prod_date"].ToString();
        glassrec.GreenTime = sdr["GreenTime"].ToString();
        glassrec.YellowTime = sdr["YellowTime"].ToString();

        glass.Add(glassrec);

    }

    JavaScriptSerializer js = new JavaScriptSerializer();
    Context.Response.Write(js.Serialize(glass));
}

我还在这篇文章中附加了我的 jquery 代码。如何进一步进行

$.ajax({
        url: "Add_Data.aspx/GetData",
        method: "post",
        datatype: "json",
        data: '',
        contentType: "application/json; charset=utf-8",

        success :function(data){
            $('$tblglass').dataTable(
                {
                    data:data,
                    columns: [
                        { 'data': 'Date' }, { 'data': 'GreenTime' }, { 'data': 'YellowTime' }
                    ]
                })
        },

        error: function (err) {
            alert('Object Not Found');
        }
    });
};

标签: javascriptjqueryasp.net

解决方案


发生错误是因为GetData()Web 服务方法设置为static,只需将其设置为非静态方法即可。此外,您可能需要使用[ScriptMethod(ResponseFormat = ResponseFormat.Json)]属性装饰方法并将返回类型更改为void(当前您没有返回任何带有return语句但返回类型设置为string),如下例所示:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetData()
{
    List<Glassrecord> glass = new List<Glassrecord>();

    // database connection code here

    JavaScriptSerializer js = new JavaScriptSerializer();

    Context.Response.ContentType = "application/json";
    Context.Response.Write(js.Serialize(glass));
}

相关问题:如何从 3.5 asmx Web 服务获取 JSON 响应


推荐阅读