简体   繁体   中英

Can't pass variable from JQuery AJAX to C# code behind

Not sure what I'm doing wrong but I can't get my JQuery AJAX call to pass the variable properly. It recieves it just fine. I'm probably overlooking something minor. Thanks.

(Also, is there any way to pass data this way without using a [WebMethod] or via the URL?)

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {   
            $('#button').click(function(){
            var json_obj = "{'" + $('#t1').val() + "' : '" + $('#p1').val() + "', '" + $('#t2').val() + "' : '" + $('#p2').val() + "'}";

                $.ajax({
                    type: "POST",
                    url: 'Default.aspx/test',
                    contentType: 'application/json; charset=utf-8',
                    data: "thisisatest",//json_obj,
                    dataType: 'json',
                    success: function(msg) {
                    //$('#result').html(msg.d);
                        alert(msg.d)
                    },
                    error: function(msg) {
                    //$('#result').html(msg.d);
                        alert(msg.d + " err")
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div>
        Type: 1: <input type="text" id="t1" />
        Property 1: <input type="text" id="p1" />
        <br /><br />
        Type 2: <input type="text" id="t2" />
        Property 2: <input type="text" id="p2" />
        <input type="button" value="Add object!" id="button" />
        <br /><br />
        <div id="result"></div>
    </div>
</body>
</html>

Code Behind

    [WebMethod]
    public string test(string json)
    { 
        return json;
    }

WebMethods must be static!

http://encosia.com/why-do-aspnet-ajax-page-methods-have-to-be-static/

[WebMethod]
public static string test(string json)
{ 
   return json;
}

and your JSON input should be :

var jsonInput = { 'json': 'XXXXXXX'};

where 'json' is equal to the name of the webmethod parameter

and in the Ajax function

data:JSON.stringify(jsonInput)

Here's a full example I wrote for you to illustrate the concept:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<script type="text/C#" runat="server">

    public class MyModel
    {
        public string T1 { get; set; }
        public string P1 { get; set; }
        public string T2 { get; set; }
        public string P2 { get; set; }
    }

    [WebMethod]
    public static string Test(MyModel obj)
    {
        return "Hello from test";
    }
</script>

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    Type: 1: <input type="text" id="t1" />
    Property 1: <input type="text" id="p1" />
    <br /><br />
    Type 2: <input type="text" id="t2" />
    Property 2: <input type="text" id="p2" />
    <input type="button" value="Add object!" id="button" />
    <br /><br />
    <div id="result"></div>

    <script src="scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $('#button').click(function () {
            var data = JSON.stringify({
                obj: {
                    t1: $('#t1').val(),
                    p1: $('#p1').val(),
                    t2: $('#t2').val(),
                    p2: $('#p2').val()
                }
            });
            $.ajax({
                url: 'default.aspx/test',
                type: 'POST',
                contentType: 'application/json',
                data: data,
                success: function(result) {
                    $('#result').html(result.d);
                }
            });
            return false;
        });
    </script>
</body>
</html>

I have mixed here the code behind and the markup in the same Default.aspx file but obviously you could have them separate if you prefer.

You can change the method to GET and append the value to the URL like so...

$.ajax({
     type: "GET",
     url: 'Default.aspx/test?json=' + 'thisisatest',
     contentType: 'application/json; charset=utf-8',
     success: function(msg) {
          //$('#result').html(msg.d);
          alert(msg.d)
     },
     error: function(msg) {
          //$('#result').html(msg.d);
          alert(msg.d + " err")
     }
});

Then in your code behind....

protected void Page_Load(object sender, EventArgs e)
{
     Response.ContentType = "application/json; charset=utf-8";
     Response.Write(Request["json"]);
}

If You're going to go this route though, I'd recommend not using Code Behinds as they have to process the entire ASP.NET Web Forms Page Life Cycle. You're better of using ASP.NET Handlers (ashx).

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM