Thursday, June 5, 2008

SPItemEventReceiver.ItemUpdating + Redirecting to Custom Page

This shows How redirecting to new page inside the SPItemEventReceiver.ItemUpdating event.


class CustomEventHandler: SPItemEventReceiver {

private HttpContext currentContext = null;

public CustomEventHandler()
: base()
{
if (null != HttpContext.Current)
{
currentContext = HttpContext.Current;
}
}

public override void ItemUpdating(SPItemEventProperties properties)
{
SPSite siteColl = new SPSite(properties.SiteId);
SPWeb site = siteColl.OpenWeb(properties.RelativeWebUrl);
SPList list = site.Lists[properties.ListId];

// Add the item and fill it with the values from properties
DisableEventFiring();
SPListItem itemToUpdate = properties.ListItem;
this.CloneItem(itemToUpdate, properties);


itemToUpdate.update();
EnableEventFiring();

SPUtility.Redirect(site.Url + "/ThankYou.aspx",
SPRedirectFlags.Default, currentContext);

site.Dispose();
siteColl.Dispose();
}
}
}

Note : You can only redirect inside the ItemAdding, ItemUpdating,ItemDeleting events only. Becuae in ItemAdded , ItemDeleted and ItemUpdated context is null.