The security validation for this page is invalid – Updating a SharePoint list item

Posted: December 7, 2009 in Errors

“The security validation for this page is invalid. Click Back in your Webbrowser, refresh the page, and try your operation again.”

You may always get this exception when you try to update a list item using code.

For reasons of security, Microsoft Windows SharePoint Services by default does not allow you to make posts from a Web application to modify the contents of the database unless you include security validation on the page making the request.

I too faced this issue. Below is my code snippet.

I used the below method to update a column value.

Public void updateItemValue(int intID)

{

using (SPSite site = new SPSite(parentSiteUrl))

{

site.AllowUnsafeUpdates = true;

using (SPWeb web = site.OpenWeb())

{

web.AllowUnsafeUpdates = true;

SPList list = web.Lists[“Test”];

listItem = list.Items[intID];

listItem[“Name”] = “Sharepoint”;

listItem.Update();

}

}

}


And the  below method to update the attachment.

Public void updateAttachment(int intID)

{

If(fileUpload.HasFile)

{

using (SPSite site = new SPSite(parentSiteUrl))

{

site.AllowUnsafeUpdates = true;

using (SPWeb web = site.OpenWeb())

{

web.AllowUnsafeUpdates = true;

SPList list = web.Lists[“Test”];

listItem = list.Items[intID];

listItem.Attachments.Add(strFileName,AddFile(strFilePath))

listItem.Update();

}

}

}

}


Here I came to know, when I use two SPSite objects to update a list item it gives this error.

So I changed this code and combined the method as below

Public void updateAttachment(int intID)

{

using (SPSite site = new SPSite(parentSiteUrl))

{

site.AllowUnsafeUpdates = true;

using (SPWeb web = site.OpenWeb())

{

web.AllowUnsafeUpdates = true;

SPList list = web.Lists[“Test”];

listItem = list.Items[intID];

listItem[“Name”] = “Sharepoint”;

If(fileUpload.HasFile)

{

listItem.Attachments.Add(strFileName,AddFile(strFilePath))

}

listItem.Update();

}

}

}

Now my code is  working fine. So never use 2 SPSite objects to update a single item.

You can also turn off this default feature of SharePoint.Check here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s