If you are getting the following error while Attaching a EventHandler on a Sharepoint List, than follow these three steps to resolve that issue..
Error: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.
Solution: Add the following Lines in you List Update code:
1. SPSecurity.RunWithElevatedPrivileges(delegate(){ - See Line 01
2. Add site.RootWeb.AllowUnsafeUpdates = true; , See Line 04
3. Add site.WebApplication.FormDigestSettings.Enabled = false;, See line 10
Sample Code
SPSecurity.RunWithElevatedPrivileges(delegate(){
using (SPSite site = new SPSite(URL))
{
site.RootWeb.AllowUnsafeUpdates = true;
using (SPWeb siteWeb = site.OpenWeb())
{
SPList list = siteWeb.Lists["TestList"];
SPEventReceiverDefinition defItemAdding = list.EventReceivers.Add();
site.WebApplication.FormDigestSettings.Enabled = false;
defItemAdding.Assembly = "WSPBuilderProject1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e0a58138cf93116a";
defItemAdding.Class = "WSPBuilderProject1.TestListEH";
defItemAdding.Name = "AddingEventHandler";
defItemAdding.Type = SPEventReceiverType.ItemAdding;
defItemAdding.SequenceNumber = 1001;
//defItemAdding.Synchronization = SPEventReceiverSynchronization.Synchronous;
defItemAdding.Update();
site.WebApplication.FormDigestSettings.Enabled = true;
}
site.RootWeb.AllowUnsafeUpdates = false;
}
});
Enjoy Sharepoint Green Coding @ Code4Green.com
No comments:
Post a Comment