Wednesday, February 19, 2014

Display notifications in SharePoint from code behind

Introduction

Sometimes we may need to display notifications in SharePoint; which appears on the right side of the page below the ribbon.

Problem Background

We may need to call the notification from the code behind which I will show how to achieve it.

Solution Background

We have to call SP.UI.Notify class to add and remove notification. This class contain two methods


  • addNotification – Add a notification to the page and returns the id of that notification.
  • removeNotification – Removes the notification from the page. 

Solution
 

   
private void ShowNotification()
        {
            var scriptTemplate = @"
ExecuteOrDelayUntilScriptLoaded(function(){{
    ExecuteOrDelayUntilScriptLoaded(function(){{
            var notificationId = SP.UI.Notify.addNotification(""{0}"", false);
//false here will remove the notification in 5 secs
//true will not remove until we remove it by calling removeNotification   
        }},
    'core.js'
    )}},
'sp.js'
);";
            //You can give the string in Hello World!!
            var script = string.Format(scriptTemplate, "Hello World!!");
            //Here Any String as the key of the client script to register
            Page.ClientScript.RegisterClientScriptBlock(GetType(), "Any String", script, true);
        }

Use removeNotification to remove the notification explicitly.

   
private void ShowNotification()
        {
            var scriptTemplate = @"
    ExecuteOrDelayUntilScriptLoaded(function(){{
        ExecuteOrDelayUntilScriptLoaded(function(){{
            var notificationId = SP.UI.Notify.addNotification(""{0}"", true);
            removeNotification(notificationId);//remove the notification. 
        }},
    'core.js'
    )}},
'sp.js'
);";
      
            var script = string.Format(scriptTemplate, "Hello World!!");
            Page.ClientScript.RegisterClientScriptBlock(GetType(), "Any String", script, true);
        }

Conclusion

Please go through below urls for more information on this. 

No comments:

Post a Comment