javascript - 非静态字段、方法或属性“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');
}
});
};
解决方案
发生错误是因为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));
}
推荐阅读
- c++ - 具有自定义分配器的类
- ios - iOS 13 使用 SwipeKeyboard 和 textfield 崩溃:shouldChangeCharactersIn:
- reactjs - 在 React 中,当下拉列表值发生变化时,如何获取下拉列表的 ID?
- amazon-web-services - 将请求转发到 AWS 上的多个目标服务器
- sql - VBA SQL 查询中的问题引用列
- r - 在每个逗号后查找第二个空格
- php - 如何在 Wordpress 中将子类别添加到多个父类别
- swiftui - 如何在 SwiftUI 中为 WebView 实现刷新按钮
- java - Spring Rest 在上下文中设置自定义对象
- c - 写入系统调用表函数地址时内核模块崩溃