Tuesday, December 2, 2008

Redirecting from NewForm.aspx to DispForm.aspx after creating a new item

public class CustomEventReceiver : SPItemEventReceiver
{
  private HttpContext _currentContext = null;
 
  public CustomEventReceiver () : base ()
  {
  if (null != HttpContext.Current)
  {
  _currentContext = HttpContext.Current
  }
  }
 
  public override void ItemAdding (SPItemEventProperties properties)
  {
  using(SPSite site = new SPSite(properties.SiteId))
  {
  using(SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
  {
  SPList list = web.Lists[properties.ListId];

  DisableEventFiring();
  SPListItem itemToAdd = list.Items.Add();
  foreach (SPField field in itemToAdd.Fields)
  {
  if (!field.Hidden && !field.ReadOnlyField && field != null && field.InternalName != "Attachments")
  {
  itemToAdd[field.InternalName] = properties.AfterProperties[field.InternalName];
  }
  }
  itemToAdd.Update();
  EnableEventFiring();


  // Redirect
  SPUtility.Redirect("/cn/Lists/Bills%20of%20Lading/DispForm.aspx?ID=" + itemToAdd.ID, SPRedirectFlags.Default, _currentContext);
  }
  }
  }
}

2 comments:

CB Corstorphine said...

Where do you place this code?

Tomas said...

This is event receiver on item adding