vrijdag 15 april 2011

Doing a redirect in ItemUpdated event

Sometimes it might be handy to, based on an update of an item, redirect the user to a different page. For example, if a given metadata field of the item has a certain value, redirect the user to another page.

Although this request seems fairly simple, it's not so easy to do. Why?

1. If you want to do it during ItemUpdating, your event thread will not be finished and your item will not actually be updated.
2. If you do it during ItemUpdated, you will not have access to the HttpContext so you cannot use SPUtility.Redirect. Or can you ... ? :) I really lost a day or more searching for this but now have a working solution.

It seems that with some workarounds, you can have access to the HttpContext in the ItemUpdated. I will here briefly explain how to do it:

1. Create two private global variables in your event receiver:
private HttpContext _httpContext;
private static HttpContext _sHttpContext;

2. Get a hold of the HttpContext in the constructor
_httpContext = HttpContext.Current;

3. In ItemUpdating, again get a hold of the HttpContext
_sHttpContext = _httpContext

4. Use SPUtility.Redirect and _sHttpContext to redirect to a page of your choice.

3 opmerkingen:

  1. Frank, thanks a lot.
    But when I use SPUtility.Redirect in ItemUpdated event my page opens in Modal window.
    How I can redirect to new window?

    Thanks again.

    BeantwoordenVerwijderen
  2. I found a solution.

    In httpResponse write javascript with next content: window.frameElement.navigateParent('redirectURL')
    then call
    _sHttpContext.Response.Flush(); _sHttpContext.Response.End();

    BeantwoordenVerwijderen
    Reacties
    1. Hey Tappi,

      can you elaborate a bit more in detail what to do?
      i am facing the same issue.

      where do i need to insert the javascript?
      where do i call the flush and response end?

      Thx in advance!
      Tobias

      Verwijderen