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...!!!

4 comments:

  1. Ok, but what to do if HttpContext.Current comes out NULL in constructor?

    ReplyDelete
    Replies
    1. Hi Senglory,\

      you have to use Synchronous event handler because Synchronous method only get HttpContext.Current value.

      Delete
  2. It redirects in the NewDisp.aspx form but not the parent form. I can't find a way to redirect the parent form....annoying.

    ReplyDelete
  3. getting httpcontext null in constructor. I am developing ItemAdding event receiver for SharePoint online site. Do you have any suggestion please to successfully get the httpcontext object?

    ReplyDelete