• Skip to main content
  • Skip to primary sidebar

Technical Notes Of
Ehi Kioya

Technical Notes Of Ehi Kioya

  • About
  • Contact
MENUMENU
  • Blog Home
  • AWS, Azure, Cloud
  • Backend (Server-Side)
  • Frontend (Client-Side)
  • SharePoint
  • Tools & Resources
    • CM/IN Ruler
    • URL Decoder
    • Text Hasher
    • Word Count
    • IP Lookup
  • Linux & Servers
  • Zero Code Tech
  • WordPress
  • Musings
  • More
    Categories
    • Cloud
    • Server-Side
    • Front-End
    • SharePoint
    • Tools
    • Linux
    • Zero Code
    • WordPress
    • Musings
Home » Backend (Server-Side) » Call SharePoint Server Side Method With JavaScript

Call SharePoint Server Side Method With JavaScript

By Ehi Kioya Leave a Comment

Although the technique I describe here for calling a server side method with JavaScript is related to SharePoint, it can very easily be adapted to a pure C# and ASP.NET implementation.

This discussion is related to my previous two posts about working with the SharePoint edit control block and the Sharepoint ribbon programmatically. This is a technique I have often found useful when working with ASP.NET forms called as modal dialogs with JavaScript in SharePoint. I will describe how to call a SharePoint server side method with JavaScript after closing a modal dialog by pressing OK or Cancel. I will also show how you may pass parameters.

When our modal dialog is still open, we can easily interact with server side methods the usual way via controls and events. But what happens if you want to close a modal dialog and then pass control to a method contained in another .aspx page? And how would you pass any parameters? The answer is demonstrated with code snippets below.

To give the code some perspective, I have borrowed some code from one of my previous posts: Add Custom Action To SharePoint Edit Control Block. You may need to refer to that post to get the full picture and see how this piece includes an enhancement.

The JavaScript That Opens The Modal Dialog

Here’s the relevant JavaScript code snippet (the parameter we’re passing is {ItemId}).
One of the things to be aware of is the value of dialogReturnValueCallback property, the value is the name of the function that will be called after the popup window is closed.

.
.
.
SPUserCustomAction customaction = list.UserCustomActions.Add();
customaction.Name = "ECBItemCustomization";
customaction.Location = "EditControlBlock";
customaction.ImageUrl = "//cdn.ehikioya.com/_layouts/images/dummyproject/workflows.gif";
string cAction = @"javascript: function CloseCallback(dialogResult, returnValue) {
         if (dialogResult == SP.UI.DialogResult.OK) {
             $.ajax({
                 type: 'POST',
                 url: '/_layouts/dummyproject/PageToGiveControl.aspx/MethodToCall',
                 data: '{data: ' + returnValue + '}',
                 contentType: 'application/json; charset=utf-8',
                 dataType: 'json',
                 success: function (msg) {
                 }
             });
         }
     }
     var options = {
         url: '{SiteUrl}' + '/_layouts/dummyproject/YourModalDialog.aspx/?ItemID={ItemId}',
         allowMaximize: false,
         width: 360,
         height: 150,
         dialogReturnValueCallback: CloseCallback };
     SP.UI.ModalDialog.showModalDialog(options);";
customaction.Url = cAction;
customaction.Sequence = 106;
customaction.Title = "Dummy Title";
customaction.Update();
list.Update();
.
.
.

The JavaScript On The Modal Dialog Page

In order for this to work, of course you need to have a modal dialog page called YourModalDialog.aspx. We will also add some JavaScript to this page. Add a content place holder for the head section of the page. Here’s how the head section code for YourModalDialog.aspx will look like:

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script  type="text/jscript">
        var prmstr = window.location.search.substr(1);
        var prmarr = prmstr.split("&");
        var params = {};

        for (var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
            params[tmparr[0]] = tmparr[1];
        }

        function ClosePopupCancel() {
            SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancel clicked');
        }

        function ClosePopupOk() {
            SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, params.ItemID);
        }
    </script>
</asp:Content>

Some ASP.NET Code On The Modal Dialog Page

Now in the main content place holder, you will create a form with input buttons for OK and Cancel. The onclick event of each of these buttons should call the corresponding JavaScript method created above. For brevity, here’s a snippet of the code for the main content area.

.
.
.
<td>
    <input type="button" value="OK" onclick="ClosePopupOk();" style="width:100px;" />
</td>
<td>
    <input type="button" value="Cancel" onclick="ClosePopupCancel();" style="width:100px;" />
</td>
.
.
.

The C# Server Side Method On The Called Page

Now we create another .aspx page called PageToGiveControl.aspx. And we add a page method called MethodToCall.

Writing a page method is easy. They must be declared as static, and they must be decorated with the [WebMethod] attribute. Beyond that, ASP.NET AJAX takes care of the rest on the server side.

By adding the [WebMethod] attribute as shown, this method becomes accessible from JavaScript.
This will be our page method for the example:

[WebMethod]
public static void MethodToCall(Object data)
{
    int itemID = Convert.ToInt32(data);
    // Now you can do something with itemID.
}

At this point we have pressed the OK button on the modal dialog. The modal dialog closes and control (plus the ItemID parameter) is smoothly transferred to the new page (PageToGiveControl.aspx) via the web method (MethodToCall).

Do you know of any way this code could be made simpler and still achieve all of it objectives? If so, please don’t hesitate to add your comments below.

Found this article valuable? Want to show your appreciation? Here are some options:

  1. Spread the word! Use these buttons to share this link on your favorite social media sites.
  2. Help me share this on . . .

    • Facebook
    • Twitter
    • LinkedIn
    • Reddit
    • Tumblr
    • Pinterest
    • Pocket
    • Telegram
    • WhatsApp
    • Skype
  3. Sign up to join my audience and receive email notifications when I publish new content.
  4. Contribute by adding a comment using the comments section below.
  5. Follow me on Twitter, LinkedIn, and Facebook.

Related

Filed Under: Backend (Server-Side), Frontend (Client-Side), JavaScript, SharePoint Tagged With: JavaScript, SharePoint

About Ehi Kioya

I am a Toronto-based Software Engineer. I run this website as part hobby and part business.

To share your thoughts or get help with any of my posts, please drop a comment at the appropriate link.

You can contact me using the form on this page. I'm also on Twitter, LinkedIn, and Facebook.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

23,569
Followers
Follow
30,000
Connections
Connect
14,568
Page Fans
Like
  • Recently   Popular   Posts   &   Pages
  • Actual Size Online Ruler Actual Size Online Ruler
    I created this page to measure your screen resolution and produce an online ruler of actual size. It's powered with JavaScript and HTML5.
  • How To Install PHP Packages Without Composer How To Install PHP Packages Without Composer
    This article shows how to bypass the Composer barrier when installing Composer-dependent PHP packages. Great shortcut for PHP enthusiasts!
  • Fix For “Function create_function() is deprecated” In PHP 7.2 Fix For "Function create_function() is deprecated" In PHP 7.2
    As of PHP 7.2 create_function() has been deprecated because it uses eval(). You should replace it with an anonymous function instead.
  • About
  • Contact

© 2022   ·   Ehi Kioya   ·   All Rights Reserved
Privacy Policy