Showing posts with label EventHandler. Show all posts
Showing posts with label EventHandler. Show all posts

Tuesday, October 25, 2011

Using HTTPContext object Redirect Page from EventHandler

We need to display custom page redirection after adding list item.
We have to implement Synchronous event handler for above list because we can get HttpContext in Synchronous event handler & redirect to custom page using SPUtility.Redirect method.
See the below code for redirect custom page after adding list item. 
public class SyncEventReceiver : SPItemEventReceiver
    {
        HttpContext current;

        public SyncEventReceiver() { current = HttpContext.Current; }

        /// 
        /// An item is being added.
        /// 
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);

            SPSite oSite = new SPSite(properties.SiteId);
            SPWeb oWeb = oSite.OpenWeb(properties.RelativeWebUrl);
            SPList oList = oWeb.Lists[properties.ListId];

            //Set Enable Event Firing to False for disable reoccurence of events.
            this.EventFiringEnabled = false;
            
            SPListItem newItem = oList.Items.Add();
            //add item to list (you can add custom code here)
            newItem["Title"] = properties.AfterProperties["Title"].ToString();
            newItem.Update();

            //Set Enable Event Firing to True
            this.EventFiringEnabled = true;

            //redirect it to your new destination like newly provisioned sub site or any other page you want.
            SPUtility.Redirect("http://localhost/pages/default.aspx", SPRedirectFlags.Default, current);

        }

}
Happy Coding...!!!

Difference between Synchronous and Asynchronous events

Synchronous Events

  - Fire “before” the actual events
  - You can get HttpContent
  - You can display error message
  - You can cancel the event.
  - Synchronous methods ending with “ing” like itemadding, itemupdating itemdeleting.




Asynchronous Events
  - Fire “after” the actual events
  - You cannot get HttpContent
  - You cannot display error message
  - You cannot cancel the event
  - Asynchronous methods ending with “ed” like itemadded, itemupdated, itemdeleted etc.


Happy Coding...!!!