Error updating Sharepoint List item, when called from web service
I'm using ajax to call a webservice which updates a sharepoint list.
It works when I call the code from unit tests, but running the code in a browser causes an exception:
System.InvalidOperationException: Operation is not valid due to the current state of the object. at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context) at Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(HttpContext context) at Microsoft.SharePoint.SPContext.get_Current() at Microsoft.SharePoint.SPListItem.AddOrUpdateItem(Boolean bAdd, Boolean bSystem, Boolean bPreserveItemVersion, Boolean bNoVersion, Boolean bMigration, Boolean bPublish, Boolean bCheckOut, Boolean bCheckin, Guid newGuidOnAdd, Int32& ulID, Object& objAttachmentNames, Object& objAttachmentContents, Boolean suppressAfterEvents) at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, Boolean bPreserveItemVersion, Guid newGuidOnAdd, Boolean bMigration, Boolean bPublish, Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin, Boolean suppressAfterEvents) at Microsoft.SharePoint.SPListItem.Update()
My code to update the list item is:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteURL))
{
using (SPWeb web = site.OpenWeb(path))
{
SPList userProfile = web.Lists[userList];
SPQuery qry = new SPQuery
{
Query =
"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" +
accountName +
"</Value></Eq></Where><ViewFields><FieldRef Name='ID' /><FieldRef Name='Title' /><FieldRef Name='LastUpdated' /><FieldRef Name='Reaso开发者_开发技巧n' /></ViewFields>"
};
SPListItemCollection spListItemCollection = userProfile.GetItems(qry);
if (spListItemCollection.Count == 1)
{
//edit user
SPListItem item = spListItemCollection[0];
item["Updated"] = DateTime.Now;
item["Reason"] = updateReason;
item.Update();
}
}
}
});
It errors on item.Update();
Try adding this:
HttpContext context = HttpContext.Current;
if (HttpContext.Current != null)
{
if (context.Items["HttpHandlerSPWeb"] == null)
context.Items["HttpHandlerSPWeb"] = site.RootWeb;
if (context.Items["Microsoft.Office.ServerContext"] == null)
context.Items["Microsoft.Office.ServerContext"] = ServerContext.GetContext(site);
}
The problem was with security. The following line needs to be added (although not ideal)
web.AllowUnsafeUpdates = true;
I also removed the line
SPSecurity.RunWithElevatedPrivileges(delegate()
and changed the SPSite and SPWeb to not use "using".
精彩评论