WebMethods in SharePoint using JQuery

Lets say we have a SharePoint Site Page or Application Page which has a server side method and we would like to call this method from JavaScript code. Wouldn’t it be great if we can do the server side processing and return the result such as a string or a json object back to the client side? Well, this is precisely what we can do using WebMethod framework.

Lets start off by adding a simple WebMethod to a SharePoint page. Lets say we have added the below code to a page in “http://servername/site/WebMethod.aspx”. We decorate the method with [WebMethod] attribute. [ScriptMethod] is the attribute which allows us the client side access. Also note that we make the WebMethod static.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetServerDetails(string name)
{
    return "Hi " + name + ":from WebMethod";
}

Then from the JavaScript, we can call the WebMethod by appending the page url and the WebMethod name. We use this string to make an ajax post request. If we need to pass a parameter to the method we have to stringify the object. Below is the client side code:

var methodUrl = "http://servername/site/WebMethod.aspx/GetServerDetails";
var param = {};
param.name = "Prashanth";

$.ajax({
  type: "POST",
  url: methodUrl,
  data: JSON.stringify(param),
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (result) {
    var output = result.d;
  }
  error: function (jqXHR, textStatus, errorThrown) {
    alert('Error occured');
    if (jqXHR.status == 500) {
      console.log('Internal error: ' + jqXHR.responseText);
  } else {
    console.log('Unexpected error.');
  }
}

Instead of returning a simple string from the WebMethod, if we wanted to return a json object, we need to create a class and return an object of that class. For example, if we wanted to return address details, we can have an Address class which has the properties which encapsulates all the related data.

public class Address
{
  public string HouseNumber {get; set;};
  public string Street {get; set;};
  public string City {get; set;};
  public string Pin {get; set;};
  public string Country {get; set;};
}

Then in the WebMethod, we create object of this class and return the same. We will then receive the json object containing the Address data on the client side. We can even return arrays of strings and objects. We would then receive the collection inside the json object.

Get Free Email Updates!

Signup now and receive an email once I publish new content.

I will never give away, trade or sell your email address. You can unsubscribe at any time.

  • Jesus Hernandez

    hi, i have a question..
    I have a visual web part in the code put a web method, after in one page of share point, add the web part but when i try call the method the response say: Error, I don’t know why do you have any idea?

    thanks

    my code in the ascx.cs
    [WebMethod()]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string hola()
    {
    return “hola mundo”;
    }

    in the jquery

    function ShowCurrentTime() {

    $.ajax({
    type: “POST”,
    url: “Directorio.aspx/hola”,
    contentType: “application/json; charset=utf-8”,
    dataType: “json”,
    success: OnSuccess,
    failure: function (response) {
    alert(response.d);
    }
    });
    }
    function OnSuccess(response) {
    alert(response.d);
    }