In ASP.NET Web Forms, i am able to call page method using Ajax "post" request. But i am not able to call the page method using "get request".
In this case, is it possible to call page methods using "Get" request.?Could you please provide any suggestion for this? Example Code for Page method:
[WebMethod]
public static string GetData()
{
return "test";
}
As @vc mentioned in the comments you'll need to make use of the ScriptMethodAttribute
as well as WebMethod
because you want your request to be GET
and not POST
so change your code as follows:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetData()
{
return "test";
}
And in the markup you can do
function ShowTestMessage() {
$.ajax({
type: "GET",
url: "YourPage.aspx/GetData",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
<input id="ButtonId" type="button" value="Show Message"
onclick = "ShowTestMessage()" />
Don't forget to add the following reference
using System.Web.Script.Services;
using System.Web.Services;
Ajax GET requests to an ASP.NET Page Method?
I guess the link would be useful. It says For security reasons, ASP.Net AJAX page methods only support POST requests.
Tried decorating the method with [ScriptMethod(UseHttpGet = true)] but still the get request is not hit.
Also the msdn doc for [ScriptMethod(UseHttpGet = true)] quotes When this property is set to true, the client proxy code uses HTTP GET to call the Web service. Not sure if it works for a webmethod in web forms.
P.S : Well seems to work with the newer versions of Jquery 2.2.2. Also please be sure that you send data through query strings not using request body as in POST method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With