我试图使用PageMethods(AJAX)在c#方法后面调用一个非常简单的代码。我有EnablePageMethods = true
并将我的代码作为WebMethod公共静态方法。我也尝试过使用WebMethod的ScriptMethod,但没有任何效果。我也试过更改配置文件,但没有运气。
<script type="text/javascript">
function ShowAvailability() {
PageMethods.btnCheck_Click(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess)
};
function OnSuccess(response) {
alert("On Success");
var mesg = document.getElementById("mesg");
switch (response) {
case "true":
mesg.style.color = "green";
mesg.innerHTML = "Available";
break;
case "false":
mesg.style.color = "red";
mesg.innerHTML = "Not Available";
break;
case "error":
mesg.style.color = "red";
mesg.innerHTML = "Error occured";
break;
}
}
function OnChange(txt) {
document.getElementById("mesg").innerHTML = "";
}
function test()
{
}
</script>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<div>
UserName :
<asp:TextBox ID="txtUserName" runat="server"
onkeyup="OnChange(this)"></asp:TextBox>
<%--<asp:Button ID="btnCheck" runat="server" Text="Show Availability" OnClientClick="btnCheck_Click(), return false;"></asp:Button>--%>
<br />
<button id="btncheck" onclick="ShowAvailability()">Show Availability</button>
<span id="mesg"></span>
</div>
</form>
答案 0 :(得分:0)
使用OnClientClick,你无法调用代码隐藏方法,它会调用名为btnCheck_Click的脚本函数。
Use this-
<asp:Button ID="btnSearch" runat="server" ClientIDMode="Static" Text="Search" CssClass="button" OnClick="btnSearch_Click" />
并在同一页面后面的代码中使用 -
protected void btnSearch_Click(object sender, EventArgs e)
{
//your code
}
如果你想使用ajax。然后在客户端声明 -
Use this-
<asp:Button ID="btnSearch" runat="server" ClientIDMode="Static" Text="Search" CssClass="button" OnClientClick="btnSearch_Click()" />
并在Script标签中调用ajax
function btnSearch_Click()
{
jQuery.ajax({
url: "Dashboard.aspx/getUserDetails", /* getUserDetails is a web method */
type: "POST",
data: jsondata, /* jsondata= passed parameter in json format */
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { },
error: function () {
$('#Loadingimage').hide();
jAlert("Please try again later", 'Moderators');
}
});
}
并在Dashboard.aspx.cs中编写此代码
[WebMethod]
public static String getUserDetails(string strUserId)
{
return ""; /* for string only */
}