希望这是一个相当容易的问题......请原谅我的无知,我是一个PHP/Zend开发人员,但我在C#和VisualStudio中遇到了json/ajax问题。有什么东西我漏掉了吗?任何帮助都将不胜感激。或者我应该看看List<>吗?
下面是我在触发javascript Ajax函数时收到的错误:“Unknown web method getwidgets”。
我在C#中有一个DataSet,它通过JSON转换器方法运行,并以JSON字符串返回我的数据。
private widgetsBL widgetsBLObject = new widgetsBL();
[WebMethod]
public String getwidgets()
{
DataSet results = new DataSet();
results = widgetsBLObject.selectTheWidgets();
string jsresults = MyClassLibrary.JqueryTools.GetJSONString(results.Tables[0]);
return jsresults;
}
以下是jsResuls:
{"Table" : [ {"widgetid" : "1","widgetname" : "gizmo1000","widgetdescription" : "very cool widget"},
{"widgetid" : "2","widgetname" : "gizmo2000","widgetdescription" : "decent widget"},
{"widgetid" : "3","widgetname" : "gizmo3000","widgetdescription" : "terrible widget"} ]}
我的Javascript调用:
$.ajax({
type: "POST",
url: "my.aspx/getwidgets",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// do stuff with returned data
}
});
getwidgets
needs to be static
[WebMethod]
public static String getwidgets()
You are mixing technologies: my.aspx is for rendering HTML content, but it can be used to implement REST functionality.
In your case, the easiest would be to implement your code as part of the Page_Loaded() method. Make sure you clear the response first (so you don't have any additional markup in the response). Furthermore, you might want to set the content type of your response to JSON (rather than the default html):
protected void Page_Load(object sender, EventArgs e)
{
Response.ClearContent();
Response.ContentType = "application/json";
DataSet results = new DataSet();
results = widgetsBLObject.selectTheWidgets();
string jsresults = MyClassLibrary.JqueryTools.GetJSONString(results.Tables[0]);
return jsresults;
}
Then retrieve you JSON string at my.aspx (no getwidgets).
Also, since you are not posting any data, consider using GET rather than POST in your AJAX call.
Remember that if you want your method to be exposed to calls from JavaScript, you need to mark your method with ScriptMethodAttribute. Thus making it look like this:
[ScriptMethod]
[WebMethod]
public static String getwidgets()
{
// Your core here
}
I would return in the method, the object itself and not not a serialized version of it because ASP.NET will JSON serialize it for you if you mark it as [ScriptMethod]; so in the client your variable data.d will contain the object itself and not a simple string that later you have to deserialize, as in your current implementation.