REST web method and AJAX call in ASP.NET page

In this post I don’t speak about new features but an old one.
I decided to speak about it because I notice that with all the new method to create a service the old WebMethod have been forgotten.

In .Net to realize a web service there are many methods:

  • Generic Handler
  • Web service
  • WCF
  • Web API

All of these are great solution to solve our problems.
If we have to write a site and in a page we need to do an ajax call we can use all of the previous solutions, but there’s also another solution.

It’s possible write a WebMethod in the code behind of our page site, and call it using AJAX.
To do this we have to mark the method with the attribute WebMethod

[System.Web.Services.WebMethod()]
public static string Test()
{
return "sohel rana";
}

Adding WebMethod() attribute to the method permit to call our web method doing a POST
so we can call it using

POST to http://localhost/mypage.aspx/Test

If we want call the method with GET we have to add ScriptMethod

[System.Web.Services.WebMethod()]
// IMPORTANT: pass the parameter by querystring
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static string TestParGet(int id)
{
return " parametro: " + id.ToString();
}

GET to http://localhost/mypage.aspx/TestParGet?id=3

We can also return a class that will be send to the client as JSON

[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static dynamic TestClass()
{
return new { name = "tom", age = 12 };
}

Ok we have write our code behind, how can we call it using AJAX?

  1. ScriptManager
  2. JQuery

ScriptManager

Put the ScriptManager in your page and EnablePageMethods

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

Then write the javascript necessary to call the WebMethod

function callWebServiceMethodTestParGet() {
// no difference by get or post using ScriptManager
PageMethods.TestParGet(10, complete);
}

function callWebServiceMethodTestClass() {
PageMethods.TestClass(completeClass);
}

// callbacks
function complete(val) {
alert(val);
}

function completeClass(val) {
alert("Name: " + val.name + ", Age: " + val.age);
}

The ScriptManager will automatically call the method in the right way, we haven’t to worry about GET or POST.

JQuery

Using JQuery we have to write more javascript code, but we don’t litter our html page with javascript code generated automatically by ScriptManager.
I’ll show how to do a POST, a GET, and obtain JSON object
JQuery GET with parameter


function callWebServiceMethodAjaxTestParGet() {
// TestParGet
$.ajax({
type: "Get",
cache: false,
url: "http://localhost:3712/WebForm1.aspx/TestParGet?id=3",
contentType: "application/json", // IMPORTANT if you write only contentType: "json" it doesn't work!!!
beforeSend: function () { },
complete: function () { },
error: function (xhr, status, errorThrown) {
alert(errorThrown);
},
success: function (result) {
// return d object
alert(result.d);
}
});
}

Using GET we have to pass it by querystring.
Important to set contentType to “application/json” not only json.
We get the result accessing to “d” => result.d

JQuery POST with parameter

function callWebServiceMethodAjaxTestParPost() {
// TestParPOST
$.ajax({
type: "POST",
data: JSON.stringify({ // IMPORTANT use JSON.stringify, not data: {id:3}
id: 3
}),
cache: false,
url: "http://localhost:3712/WebForm1.aspx/TestParPost",
contentType: "application/json", // IMPORTANT if you write only contentType: "json" it doesn't work!!!
beforeSend: function () { },
complete: function () { },
error: function (xhr, status, errorThrown) {
alert(errorThrown);
},
success: function (result) {
// return d object
alert(result.d);
}
});
}

JQuery GET an object returned from the service

function callWebServiceMethodAjaxTestClass() {
// TestClass
$.ajax({
type: "GET",
cache: false,
url: "http://localhost:3712/WebForm1.aspx/TestClass",
contentType: "application/json", // IMPORTANT if you write only contentType: "json" it doesn't work!!!
beforeSend: function () { },
complete: function () { },
error: function (xhr, status, errorThrown) {
alert(errorThrown);
},
success: function (result) {
// return d object
alert("Name: " + result.d.name + ", Age: " + result.d.age);
}
});
}

To test it and clear all question I’ve created a project for testing: download it

Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in .Net, Asp.Net, c#, javascript, jquery e contrassegnata con , , , , , . Contrassegna il permalink.

Una risposta a REST web method and AJAX call in ASP.NET page

  1. talking to ha detto:

    Now, there are different factors involved in this process, which determines the friendliness of a website. This can be done in a number of ways including regular press releases and blog posts. To make sure that you are getting the best techniques for your business, better make sure that you have chosen the best SEO Company for your business needs.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...