Reputation: 1
I am trying to call a simple server-side HelloWorld method written in C# with an AJAX request.
Default.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type ="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
function AjaxCall() {
$.ajax(
{
type: 'post',
url: 'Default.aspx/Server_HelloWorld',
datatype: 'json',
success: function (result) { alert(result); }
})
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="Scriptmanager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
<asp:Services>
<asp:ServiceReference Path="TradeService.asmx" />
</asp:Services>
</asp:ScriptManager>
<button id="Button2" type="button" runat="server" onclick="AjaxCall()">AJAX+JQuery version</button>
</form>
</body>
</html>
Default.aspx.cs
namespace AJAXService
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public String Server_HelloWorld()
{
return "Hello, How are you?";
}
}
}
However, instead of returning the string, "Hello, How are you?", I get back the html code of the web page. Does anyone know why this happens? I am eventually trying to have a server-side method return a string that I can use to fill a GridView cell, utilizing AJAX's partial postback feature.
Upvotes: 0
Views: 9273
Reputation: 118
Yes, I think I do know why this happens! I've been having the same issue myself and have done some research.
Try using onclick="AjaxCall(); return false;"
. This cancels the usual ASP.NET onclick event (which in this case would do nothing but return to your page, that's why you're getting the page as response) and only execute your JavaScript method.
(Yes, I realize that I'm about 2 years too late, but I'll throw it out here for the ones facing the same issue).
Upvotes: 1
Reputation: 393
Use the Following Code and Check whether you still facing the problem or not,
your Ajax Call Javascript Method....
function AjaxCall() {
$.ajax(
{
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/Server_HelloWorld',
datatype: 'json',
success: function (result) { alert(result.d); }
})
}
Add following namespaces
using System.Web.Services;
using System.Web.Script.Services;
Your aspx.cs Ajax Webmethod,
[WebMethod]
[ScriptMethod]
public String Server_HelloWorld()
{
return "Hello, How are you?";
}
Hope this helps...
Upvotes: 0
Reputation: 4172
try this
[WebMethod]
public static String Server_HelloWorld()
{
return "Hello, How are you?";
}
So use WebMethod and static.
Upvotes: 1