从 ajax 调用 WebMethod,控制不进入 webmethod 内部

Calling WebMethod from ajax, control not going inside webmethod

我正在尝试调用代码隐藏方法,成功:jquery 部分的 function() 被执行,但控件似乎没有进入被调用的代码隐藏方法。 aspx 页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication6.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(document).ready(function () {

        //$("#Button1").click();

    $.ajax({
    type: "POST",
    url: '<%=ResolveUrl("WebForm1.aspx/Method1")%>',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        $("#test").html("success");
    }
    });
    })

</script>
</head>
<body>
<form id="form1" runat="server">
     <asp:ScriptManager ID="ScriptManager" runat="server" EnablePartialRendering="true" EnablePageMethods="True" />

<div>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>               
</div>
    <div id="test">initial</div>

</form>

aspx.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication6
{
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [System.Web.Services.WebMethod()]
    [System.Web.Script.Services.ScriptMethod()]
    public static void Method1()
    {
        WebForm1 w = new WebForm1();
        w.Label1.Text = "code behind";
    }

}

}

输出:

Label
success

输出让我得出结论,成功:jquery 的 function() 被执行(如 $("#test").html("success"); 被执行似乎),但 Label1 文本仍然是标签,代码隐藏方法似乎没有被执行。 为什么会这样?感谢您的帮助。

问题出在客户端与服务器端。当使用 java 脚本 Ajax 请求和 ASP.

时,您必须了解这一点

首先 JavaScript 代码是 运行 在客户端机器上,而 ASP.net 是 运行 服务器端。

当用js执行ajax请求时,它期望来自服务器的一些结果通常是json、xml、内存流。您获取此信息并在客户端对其进行处理。

当你执行类似:w.Label1.Text = "code behind";在服务器端,Web 方法请求将不起作用,因为您没有在服务器为 asp.net 控件生成值的地方进行整页刷新。

为了让你的代码工作,你应该这样写

public class Result
 {
     public string State{get;set;}
     public string Message{get;set;}
 }

public static Result Method1()
 {
     return new Result{State="Success",Message="code behind" };
 }

JS:

$.ajax({
    type: "POST",
    url: '<%=ResolveUrl("WebForm1.aspx/Method1")%>',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        $("#test").html(result.State);
        $("#Label1").html(result.Message);
    }
    });