Call C# Web method by JavaScript

29/01/2016 02:54

In this partial example we are going to use page web methods to be called by JavaScript. We create model, logic in .Net, and we use JavaScript just to display model data, errors...

We have SharePoint application page and in its code behind we have defined web methods.Then we have javascript file with web method calls

There is important to have defined constructor for our model class to enable JSON to parse it correctly.

 

javascript file or .aspx head part

 

var yourNameSpace =
{
 addMember: function (userLogin) {
        var url = _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/YourFolder/YourApplicationPage.aspx/AddUser";
        var postData = JSON.stringify({ 'userLogin': userLogin, 'model': yourNameSpace.dialogModel });

        var successFunction = function (data) {
            var model = $.parseJSON(data.d);
            yourNameSpace.dialogModel = model;
            //other functionality
        };

        yourNameSpace.callWs(url, postData, successFunction);
    },
 
 callWs: function (url, postData, successFunction) { 
        $.ajax({
            url: url,
            async: true,
            type: 'POST',
            data: postData,
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: successFunction,
            error: function (err) {
             
                alert("WS Call Error with this message:" + err.statusText);
            }
        });
    },
}
...

Atention: C# class model must have constructor

Code in YourFolder/YourApplicationPage.aspx.cs

 static readonly JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();


 [WebMethod]
 public static string AddUser(string userLogin, YourModelClass model)
 {
  var model = YourFunctionToGetModel(userLogin, model, SPContext.Current.Web);
  return JavaScriptSerializer.Serialize(model);
 }

Then you just call your method in javascript as onclick or whatever:
 
 yourNameSpace.addMember('dev\\myLogin');