Add Custom button to SharePoint ribbon with server side code to execute

To add custom button to ribbon we will need to do below things:-

1.       Create SharePoint Empty Project.

2.       Add new “Empty Element”.

3.        Map Layout folder.

4.       Add One JS file to Layout folder.

5.       Add Application Page to same folder.

6.       Crete 2 logo images

Look at below solution Structure:-

 

Output:-

Custom button will be enabled only when item is selected:-
Code:-




1.       Element.XML

<?xml version=1.0 encoding=utf-8?>

  <CustomAction Id=CustomRibbonSolution Location=CommandUI.Ribbon>

    <CommandUIExtension>

      <CommandUIDefinitions>

        <CommandUIDefinition Location=Ribbon.Documents.Copies.Controls._children>

          <Button Id=Ribbon.Documents.Copies.ExportFilteredView

                  Command=ExportFilteredView

                  Sequence=20

                  Image16by16=/_layouts/images/CustomRibbonSolution/zip_16x16.png

                  Image32by32=/_layouts/images/CustomRibbonSolution/zip_32x32.png

                  LabelText=Export Filtered View

                  Description=Export Filtered view to XSL

                  TemplateAlias=o1/>

        </CommandUIDefinition>

      </CommandUIDefinitions>

      <CommandUIHandlers>

        <CommandUIHandler

          Command=ExportFilteredView

          CommandAction=javascript:ExportFilteredView();

          EnabledScript=javascript:enable();/>

      </CommandUIHandlers>

    </CommandUIExtension>

  </CustomAction>

  <CustomAction Id=Ribbon.Library.Actions.Scripts

                Location=ScriptLink

                ScriptSrc=/_layouts/CustomRibbonSolution/CustomRibbonJsFile.js />

</Elements>

2.       CustomRibbonJsFile.js

function enable() {

    var items = SP.ListOperation.Selection.getSelectedItems();

    var itemCount = CountDictionary(items);

    return (itemCount > 0);

}

function ExportFilteredView() {

    //alert(‘hi’);

    var context = SP.ClientContext.get_current();

    this.site = context.get_site();

    this.web = context.get_web();

    context.load(this.site);

    context.load(this.web);

    context.executeQueryAsync(

        Function.createDelegate(this, this.onQuerySucceeded),

        Function.createDelegate(this, this.onQueryFailed)

    );

}

function onQuerySucceeded() {

    var items = SP.ListOperation.Selection.getSelectedItems();

    var itemCount = CountDictionary(items);

    if (itemCount == 0) return;

    var ids = “”;

    for (var i = 0; i < itemCount; i++) {

        ids += items[i].id + “;”;

    }

    //send a request to the zip aspx page.

    var form = document.createElement(“form”);

    form.setAttribute(“method”, “post”);

    form.setAttribute(“action”, this.site.get_url() + this.web.get_serverRelativeUrl() + “/_layouts/CustomRibbonSolution/ExpoerViewToXSL.aspx”);

    var hfSourceUrl = document.createElement(“input”);

    hfSourceUrl.setAttribute(“type”, “hidden”);

    hfSourceUrl.setAttribute(“name”, “sourceUrl”);

    hfSourceUrl.setAttribute(“value”, location.href);

    form.appendChild(hfSourceUrl);

    var hfItemIds = document.createElement(“input”)

    hfItemIds.setAttribute(“type”, “hidden”);

    hfItemIds.setAttribute(“name”, “itemIDs”);

    hfItemIds.setAttribute(“value”, ids);

    form.appendChild(hfItemIds);

    document.body.appendChild(form);

    form.submit();

}

function onQueryFailed(sender, args) {

    this.statusID = SP.UI.Status.addStatus(“Export to XSL:”,

        “Exporting Failed: “ + args.get_message() + Close.”, true);

    SP.UI.Status.setStatusPriColor(this.statusID, “red”);

}

function closeStatus() {

    SP.UI.Status.removeStatus(this.statusID);

}

3.       ExportViewToXSL.aspx.cs

usingSystem;

usingMicrosoft.SharePoint;

usingMicrosoft.SharePoint.WebControls;

namespaceCustomRibbonSolution.Layouts

{

    public partial class ExpoerViewToXSL : LayoutsPageBase

    {

        protectedvoid Page_Load(objectsender, EventArgs e)

        {

            //string fullDocLibSourceUrl = Request.Params[“sourceUrl”];

            //if (string.IsNullOrEmpty(fullDocLibSourceUrl)) return;

            //string docLibUrl = fullDocLibSourceUrl.Replace(SPContext.Current.Site.Url, “”);

            //SPList list = SPContext.Current.Web.GetList(docLibUrl);

            //if (!list.IsDocumentLibrary()) return;

            //string pItemIds = Request.Params[“itemIDs”];

            //if (string.IsNullOrEmpty(pItemIds)) return;

            //SPDocumentLibrary library = (SPDocumentLibrary)list;

            //string[] sItemIds = pItemIds.Split(new char[] { ‘;’ }, StringSplitOptions.RemoveEmptyEntries);

            //int[] itemsIDs = new int[sItemIds.Length];

            //for (int i = 0; i < sItemIds.Length; i++)

            //{

            //    itemsIDs[i] = Convert.ToInt32(sItemIds[i]);

            //}

            //foreach (int id in itemsIDs)

            //{

            //Write Export logic here

            //}

            Response.Redirect(http://www.google.com&#8221;);

        }

    }

}

One thought on “Add Custom button to SharePoint ribbon with server side code to execute

Leave a reply to Satish Gadekar Cancel reply