如何在 jQuery 中调用 C# 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19701658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call C# method in jQuery?
提问by aravind
I am using a chart which should get Input from C# for plotting the graph. I am using JSON for returning the values from C# to jQuery. Anyhow it doesn't help me, what did I do wrong?
我正在使用应该从 C# 获取输入的图表来绘制图形。我正在使用 JSON 将值从 C# 返回到 jQuery。无论如何它对我没有帮助,我做错了什么?
This is my aspx code:
这是我的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>
And this is my C# code:
这是我的 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;
}
}
采纳答案by Saranya
I tested your code and everything seems to be fine, except that I serialized the List into a string and returned.
我测试了你的代码,一切似乎都很好,只是我将 List 序列化为一个字符串并返回。
$(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);
}
Server side code:
服务器端代码:
[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;
}
And the result is:
结果是:
You can improve on using the output as source for your graph.
您可以改进使用输出作为图形源。
回答by Sid M
Instead of ajax postback, you can use PageMethods:
您可以使用 PageMethods 代替 ajax 回发:
In C# page:
在 C# 页面中:
[WebMethod]
public static List<sampledata> getall()
{
List<sampledata> data = (List<sampledata>)HttpContext.Current.Session["data"];
return data;
}
In the aspx page:
在aspx页面中:
$(document).ready(function () {
var data=PageMethods.getall(OnSuccess);
function OnSuccess() {
alert("Success");
}
});
And for using PageMethods you also need to add this in your form tag:
对于使用 PageMethods,您还需要在表单标签中添加:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
回答by Joe Enos
If you don't want to rely on Microsoft's AJAX implementation (the WebMethodAttribute
, ScriptManager
, having to worry about that .d
property of the response, etc.), you can do nice clean JSON calls using ASHX handlers. You have to do a little bit of work yourself, but you get out from under WebForms's thumb a bit by doing more traditional AJAX.
如果您不想依赖 Microsoft 的 AJAX 实现(WebMethodAttribute
, ScriptManager
,不必担心.d
响应的该属性等),您可以使用 ASHX 处理程序进行干净整洁的 JSON 调用。您必须自己做一些工作,但是通过执行更传统的 AJAX,您可以稍微摆脱 WebForms 的束缚。
For your example, the C# piece would be as follows (note the IRequiresSessionState
implementation, which makes your session available):
对于您的示例,C# 部分如下(注意IRequiresSessionState
实现,它使您的会话可用):
// something.ashx.cs
public class something : IHttpHandler, IRequiresSessionState {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "application/json";
context.Response.Write(JsonConvert.SerializeObject(context.Session["data"]));
}
public bool IsReusable { get { return false; } }
}
Your javascript call would just be a call to this something.ashx
file:
您的 javascript 调用只是对该something.ashx
文件的调用:
jQuery.ajax({
url: "something.ashx",
type: "post",
dataType: "json"
}).done(function(result) {
console.log(result);
});
You don't have any POST parameters, but if you did, you'd just have to include them in your call, and read them directly from the Request
in your handler:
您没有任何 POST 参数,但如果有,您只需将它们包含在您的调用中,并直接从Request
您的处理程序中读取它们:
jQuery.ajax({
...
data: { requestMessage: "Hello!" }
});
public void ProcessRequest(HttpContext context) {
string requestMessage = context.Request["requestMessage"]; // Hello!
...etc...
}