Skip to main content
 首页 » 编程设计

c#之webmethod 无法使用 ajax

2024年02月13日44hnrainll

我的.cs代码是

auth_reg.aspx.cs (breakpoint shows the method is never reached) 
[WebMethod] 
public void ImageButton1_Click() 
{ 
    string strScript = "<script language='JavaScript'>alert('working')</script>"; 
    Page.RegisterStartupScript("PopUp", strScript); 
} 

.html代码

<asp:ImageButton ID="imgbtnsave" runat="server" Text="Submit" ImageUrl="images/btn-submit1.jpg" src="images/btn-submit1.jpg" onmouseout="this.src='images/btn-submit1.jpg';" onmouseover="this.src='images/btn-submit.jpg';" /> 
 
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script> 
 
<script type="text/javascript"> 
    $('#imgbtnsave').click(function () { 
        $.ajax({ 
            type: "POST", 
            url: "auth_reg.aspx/ImageButton1_Click", 
            data: '{}', 
            contentType: "application/json", 
            dataType: "json", 
            success: function (msg) { 
                alert('workingajax'); 
            }, 
            error: function () { 
                alert('error'); 
            } 
        });           
    }); 
</script> 

我的代码没有调用,页面只是在点击时刷新

请您参考如下方法:

页面方法必须是静态的:

[WebMethod] 
public static void ImageButton1_Click() 
{ 
 
} 

但是您不能在页面方法中注册客户端脚本方法,因为它是静态的。

除了图像控件之外,它还是一个服务器端控件,因此 jQuery 选择器必须是:

<script type="text/javascript"> 
    $("#<%=imgbtnsave.ClientID%>").click(function () { 
        $.ajax({ 
            type: "POST", 
            url: "auth_reg.aspx/ImageButton1_Click", 
            data: '{}', 
            contentType: "application/json", 
            dataType: "json", 
            success: function (msg) { 
                alert('workingajax'); 
            }, 
            error: function () { 
                alert('error'); 
            } 
        });           
    }); 
</script>