Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP.NET Web Forms, how to call a page method using "get" request

Tags:

c#

ajax

asp.net

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";
    }
like image 634
BALA MURUGAN Avatar asked Apr 06 '16 10:04

BALA MURUGAN


2 Answers

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;
like image 79
Izzy Avatar answered Sep 24 '22 21:09

Izzy


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.

like image 20
Dilip Nandakumar Avatar answered Sep 23 '22 21:09

Dilip Nandakumar