Pages

Search This Blog

Friday, February 18, 2011

Creating User Custom Actions through Code

In one of our projects, the requirement was to create an ECB menu item on list only if its configured by administrator from a custom web part (a custom web part with check boxes to determine whether an ECB is required or not). We accomplished it through custom code using client object modal.
by creating an object of UserCustomAction and assigning properties to it.
The UserCustomAction property returns the collection of custom actions for a site collection, Web site, list ot content Types. So this means that you can assign custom action to any of these.

In the below example, I am adding a user custom action for list items.
To place the new action on the menu (the one which is displayed when you hover on a list item and click to view the ECB), the Location property specifies EditControlBlock (ECB), Sequence specifies the order of placement in relation to other user custom actions, and Url specifies an absolute path to a page that defines the action.

using System;
using Microsoft.SharePoint.Client;
namespace MyCustomAction
{
    class CreateUserCustomActionList
    {
        static void Main()
        {
            String strSiteUrl = "http://mysharepointsite/";
            ClientContext clientContext = new ClientContext(strSiteUrl);
            Web objWeb = clientContext.Web;
            List objList = objWeb.Lists.GetByTitle("Demo List");
            UserCustomActionCollection collUserCustomAction = objList .UserCustomActions;
            UserCustomAction objUserCustomAction= collUserCustomAction.Add();
            objUserCustomAction.Location = "EditControlBlock";
            objUserCustomAction.Sequence = 100;
            objUserCustomAction.Title = "Demo User Custom Action";
            objUserCustomAction.Url = strSiteUrl + @"/_layouts/DemoPage.aspx";
            objUserCustomAction.Update();
            clientContext.Load(objList,
                list => list.UserCustomActions);
            clientContext.ExecuteQuery();
        }
    }
}

No comments:

Post a Comment