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.
** original post at http://ift.tt/1LD33pT - The SharePoint Guide
by Prashanth Padebettu via Everyone's Blog Posts - SharePoint Community
No comments:
Post a Comment