如何使用jquery ajax调用C#?

我想使用jquery ajax调用C#方法,但是该方法不返回任何内容,而是直接修改aspx页面中的数据。我的调用工作正常,但是我无法通过该方法对UI进行任何更改。

jQuery:

    $(document).ready(function () {

        $('#<%=Button1.ClientID %>').click(function () {
            debugger;
            $.ajax({
                type: "GET",
                url: "WebForm1.aspx/ServerSideMethod",
                data: "{}",
                    <%--contentType: "application/json; charset=utf-8",
                dataType: "json",--%>
                async: true,
                cache: false,
                success: function (msg) {
                    alert("E");

                    $('#myDiv').text(msg.d);
                },
                error: function (err) {
                    alert("Error");
                },
                failure: function (response) {
                    alert("ror1");
                }
            })
            return false;
        });
    });  
</script>

C#:

[WebMethod]

    public string ServerSideMethod(){        
       Label1.Text="Hi";
       return "Hi ajax call to C# method";
    }

注意:仅需在函数中实现的更改,并且如果我删除了javascript中的注释部分,则ajax调用会向我抛出错误警报消息。

ServerSideMethod should be declared static:

[WebMethod]
public static string ServerSideMethod()

and you can't change Label1.Text from inside ServerSideMethod since it's static.

The server-side code can't change anything client-side.

Normally, in a non-AJAX page request, the server-side code is running statements like:

Label1.Text="Hi";

in order to build the response to the client. Once that response is sent, it's no longer under the server-side code's control. Since you're making an AJAX request from an already-rendered page, you can't modify that page (that's already in the browser) from the server.

Instead, you should render the response to the AJAX call and use JavaScript code to modify the page that's in the browser.

You're not showing the markup, so I can only guess what the selector would be. But if Label1 renders a span and uses the same id client-side then it might look like this:

$('#Label1').text('Hi');

This would be in the success callback of your AJAX call. Something like this:

success: function (msg) {
    alert("E");
    $('#myDiv').text(msg.d);

    $('#Label1').text('Hi');
}

try to uncomment your line in javascript code and add ScriptMethod attribute in your WebMethod

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)
public string ServerSideMethod(){        
   //Label1.Text="Hi";
   return "Hi ajax call to C# method";
}

And why you have Label1.Text = "Hi" ? It's impossible in a WebMethod.