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='Reason' /></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();