如何在jquery中调用c#方法?

时间:2013-10-31 08:34:31

标签: c# asp.net jquery

我使用的图表应该从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');
                }
            });

这是我的cs代码

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;

    }
}

3 个答案:

答案 0 :(得分:5)

我测试了你的代码。一切似乎都很好,除了我将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);
        }

服务器代码:

[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;

        }

,结果是

enter image description here

您可以改进使用输出作为图表的来源..

答案 1 :(得分:2)

您可以使用PageMethods

代替ajax回发

在C#页面

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

在aspx页面

$(document).ready(function () {
var data=PageMethods.getall(OnSuccess);

function OnSuccess() {
            alert("Success");

        }
});

并且对于使用PageMethod,您还需要在表单标记中添加它

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

答案 2 :(得分:1)

如果您不想依赖Microsoft的AJAX实施(WebMethodAttributeScriptManager,则必须担心响应的.d属性,等),您可以使用ASHX处理程序进行干净的JSON调用。你必须自己做一些工作,但是通过做更传统的AJAX,你可以从WebForms的大拇指中得到一点。

对于您的示例,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; } }
}

您的javascript调用只是对此something.ashx文件的调用:

jQuery.ajax({
    url: "something.ashx",
    type: "post",
    dataType: "json"
}).done(function(result) {
    console.log(result);
});

您没有任何POST参数,但如果您这样做,则只需将它们包含在您的通话中,并直接从处理程序中的Request读取它们:

jQuery.ajax({
    ...
    data: { requestMessage: "Hello!" }
});


public void ProcessRequest(HttpContext context) {
    string requestMessage = context.Request["requestMessage"]; // Hello!
    ...etc...
}