Insert a Sharepoint list item from web services
I recently wanted to use Sharepoint’s web services to manipulate a list on one of our WSS sites. I wanted to submit a list item from a remote location, so using the Lists web service (http://<server-url>/_vti_bin/lists.asmx) seemed to make sense.
There are many examples of inserting a list item in Sharepoint using the web services out there on google, and they are helpful. They tell you how the Lists api works, because its not really intuitive, as the argument to the web service is an XmlNode object. Basically, what you submit to the web service is a xml document that contains the values for the list fields that you want to add, something like this (lifted and modified from here):
string sBatch = string.Empty;
sBatch = “<Method ID=\”1\” Cmd=\”New\”>”;
sBatch += “<Field Name=\”ID\”>New</Field>”;
sBatch += “<Field Name=\”Title\”>My Title</Field>”;
sBatch += “<Field Name=\”EventDate\”>” + DateTime.Now + “</Field>”;
sBatch += “</Method>”;
This is one way to construct the xml document that you need to submit. This xml will add an item with a title of “My Title” and an Event Date of the current date/time. This code works, theres nothing wrong with it. Its just that this is the extent of the examples out there, I couldn’t find anything that was more complex, for instance, an example of inserting an item into a Sharepoint list where one of the fields in the list is a lookup to another Sharepoint list.
Consider a list where there is a Status column, which is a lookup to another list that has possible values of “Submitted”, “Approved”, “Rejected”, and “Completed”. How do you specify the value for this field? I initially tried simply inserting the text value of what I wanted, so my xml would look like this:
<Method ID=”1″ Cmd=”New”>
<Field Name=”ID”>New</Field>
<Field Name=”Title”>My Title</Field>
<Field Name=”EventDate”>3/25/2006 12:00 PM</Field>
<Field Name=”Status”>Submitted</Field>
</Method>
But this doesn’t work. After some more trial and error, I tried the index of the value that I wanted, in this case 0, because “Submitted” is the first item in the list, and presto! My item was inserted, all was good. The downside that I see to this, is that if the indices of the items change, you have to change your xml. You could get around this by querying the lookup list and finding the index of the item dynamically each time, its your call. So if you want to insert an item into Sharepoint with a field that is a lookup field, here is an example of what your xml should look like:
<Method ID=”1″ Cmd=”New”>
<Field Name=”ID”>New</Field>
<Field Name=”Title”>My Title</Field>
<Field Name=”EventDate”>3/25/2006 12:00 PM</Field>
<Field Name=”Status” Type=”Lookup”>0</Field>
</Method>
I hope this helps someone else who is scouring google for help
UPDATE: I forgot an important piece to the resulting xml. You need to include the Type attribute on the Field element, I have added it to the xml above in red, my apologies.
Pratush B said,
Wrote on October 30, 2006 @ 6:15 pm
umm..there is another way though..to make it a bit more generic for code, we can pass id#;value and avoid using type=”Lookup”.
New
My Title
3/25/2006 12:00 PM
0;#Submitted
but its better using the type=”LookUp” as it avoids incorrect values
anuj handa said,
Wrote on July 19, 2007 @ 2:03 am
I am trying to update a lookup column in the sharepoint list using the Web service.
var xmldoc1;
var batch;//The batch variable builds up the XML that we are going to submit to the SharePoint list via the SharePoint web service
batch = “” issueID “”;
xmldoc1=”
xmldoc1=xmldoc1 ” ListName ”;
xmldoc1=xmldoc1 ” batch ”;
FeedbackHTTP1=new ActiveXObject(”MSXML2.XMLHTTP.3.0″);
FeedbackHTTP1.Open(”POST”, WSSSiteURL “/_vti_bin/Lists.asmx?op=UpdateListItems”, true);
FeedbackHTTP1.setRequestHeader(”Content-Type”,”text/xml; charset=utf-8″);
FeedbackHTTP1.setRequestHeader(”SOAPAction”,”http://schemas.microsoft.com/sharepoint/soap/UpdateListItems”);
FeedbackHTTP1.onreadystatechange=LookUpReady;
FeedbackHTTP1.Send(xmldoc1);
return false;
}
function LookUpReady()
{
if (FeedbackHTTP1.readyState==4){
var xmlResponse=new ActiveXObject(”MSXML2.DOMDocument.3.0″);
xmlResponse.async=false;
xmlResponse.loadXML(FeedbackHTTP1.responseXML.xml);
}
}
But this is not throwing error and is neither updating the column ……Any Help?
SharePoint Experience: Forms Server and the anonymous users said,
Wrote on September 29, 2007 @ 11:14 am
[...] (Forms Server)http://weblog.vb-tech.com/nick/archive/2006/02/24/1453.aspx (WSS web services)http://benreichelt.net/blog/2006/3/25/Insert-a-Sharepoint-list-item-from-web-services/ (Insert an [...]
Jim Raley said,
Wrote on January 10, 2008 @ 1:36 am
I’ve successfully done this, but I recently discovered that HTML-enabled multi-line fields have a problem here: submitting such a field via JS seems to strip out the line breaks and formatting.
If I put in a couple paragraphs, even if only using the default font settings, it all gets crushed together. I have not, however, tried to hard code a sample string of HTML into the soap to see if it survives.
Thoughts or workarounds? Can we set the content type (in the request header) to something other than “text/xml”? I think that’s the problem, but I lack a solution.
Ben Runchey said,
Wrote on January 11, 2008 @ 9:30 am
Ben,
Thanks for this post. I have having to utilize many of the services on the List web service and am enjoying the syntax of CAML (not really!). Your post has made things a bit easier.
-Ben
Ben C said,
Wrote on March 26, 2008 @ 10:10 am
I have been struggling to update multiselect list columns in SharePoint. Has anyone found a away to do this.
Also I tried inserting the ID as in the above example and it works for dropdown list, however I am trying to submit a value the PRIORITY field in an Issue List, which can be (1) High, (2) Normal, or (3) Low.
When I submit a 1 it will correctly set the dropdown in Edit Item, but in View Item it will only show a 1, which may be confusing to a read only user.
Milap Shah said,
Wrote on June 17, 2008 @ 9:32 pm
I am using SharePoint WebServices to upload documents into MOSS site which is on different server. I would like to know how do I upload documents into specific folder inside a document library using webservices.
Jeff said,
Wrote on June 18, 2008 @ 3:04 pm
Just wondering if you know how to insert data into a ‘hyperlink or picture’ column? I am able to use a web service call to insert all other data types but this one I can’t do. The response xml give me error code 0×80004005 cannot complete this action. Not very helpful. Thanks.
Indu said,
Wrote on July 4, 2008 @ 3:37 am
vbscript code to add attachment to sharepoint list using web service. I can other items to sharepoint the problem is in attachments.
Farhan (London ,UK) said,
Wrote on July 30, 2008 @ 5:25 am
Thanks Dude …this article saved me !
parth said,
Wrote on October 20, 2008 @ 3:20 am
below is my code :
WbSvcAuth.Authentication sp_auth = new WbSvcAuth.Authentication();
WbSvcLists.Lists sp_list = new WbSvcLists.Lists();
sp_auth.Url = “http://amey/sites/_vti_bin/Authentication.asmx”;
sp_list.Url = “http://192.168.1.39/sites/_vti_bin/Lists.asmx”;
sp_auth.CookieContainer = new System.Net.CookieContainer();
WbSvcAuth.LoginResult _result = new WbSvcAuth.LoginResult ();
//string a = @”ASTRODCBLR\Amey.Deshpande”;
sp_list.Credentials = System.Net.CredentialCache.DefaultCredentials;
sp_auth.Credentials = System.Net.CredentialCache.DefaultCredentials;
sp_auth.Login(a, “pass@word1″);
XmlNode ndLists = sp_list.GetList(”Parth’s Lists”);
Response.Write(ndLists.OuterXml);
if (_result.ErrorCode == WbSvcAuth.LoginErrorCode.NoError)
{
System.Net.CookieCollection cc = new CookieCollection();
cc = sp_auth.CookieContainer.GetCookies(new Uri(sp_auth.Url));
// System.Net.Cookie c =cc(_result.CookieName);
System.Text.StringBuilder sb_method = new System.Text.StringBuilder();
String listGUID = “{77BF8140-45D3-423F-98BF-E335F9008618}”;
sb_method.Append(”");
sb_method.Append(”rrrr”);
sb_method.Append(”qqqqq”);
sb_method.Append(”45454″);
sb_method.Append(”");
XmlDocument x_doc = new XmlDocument();
XmlElement xe_batch = x_doc.CreateElement(”Batch”);
xe_batch.SetAttribute(”OnError”, “Return”);
xe_batch.InnerXml = sb_method.ToString();
XmlNode xn_return = sp_list.UpdateListItems(listGUID, xe_batch);
}
and i am getting error as The request failed with HTTP status 404: Not Found.
Please help me out..!!
Bart van Beurden said,
Wrote on October 21, 2008 @ 10:03 am
Hi Ben,
Thanks for you’re blog, it could helps me a lot.
I was looking for several hours on the Internet for a similar solution…
But unfortunately it don’t works for me, could you help me?
Bart
My code:
===================
My Team
My Project
Bart van Beurden said,
Wrote on October 21, 2008 @ 10:05 am
Thanks for your blog, it could helps me a lot.
I was looking for several hours on the Internet for a similar solution…
But unfortunately it don’t works for me, could you help me?
sbTeam.Append(”");
sbTeam.Append(”1;#Sitecore 1″);
sbTeam.Append(”1;#LECTRIC Smoelenboek”);
sbTeam.Append(”");
Bart van Beurden said,
Wrote on October 22, 2008 @ 2:11 am
Hi Ben,
So I will try to commit my code for the third (and hopefully the last) time..
I tried to use your way and something like this below, both ways don’t work
Method ID=’1′ Cmd=’New’
Field name=’team’ Type=’Lookup’ List=’Team’ FieldRef=’name’
Field name=’project’ Type=’Lookup’ List=’Project’ FieldRef=’name’
ben said,
Wrote on October 22, 2008 @ 9:16 am
Bart, parth:
hope you get your issues resolved. I wrote this over two years ago and I haven’t done any Sharepoint work since then, so I’m really not your best option as far as getting help. The code that I posted worked for my scenario, but Sharepoint is a complex beast, and there are changes in Sharepoint 2007 that probably make my code not work anymore.
Sorry I can’t be of more help.
Rob Volk said,
Wrote on February 25, 2009 @ 11:33 am
It looks like the lookup lists require a 1-based index, not a 0-based index. Has anyone else seen this?
Ryan Lege said,
Wrote on April 6, 2009 @ 8:43 am
How about updating Modified by and Created by?
scotty said,
Wrote on April 7, 2009 @ 4:52 am
Ben,
many thanks for this post
I blew off many hours trawling through the MS examples and the many examples on t’internet which generally just repeat the MS ones trying to figure out how to update a lookup field (1-based works for me)
Finding sharepoint to be a horribly complex monster to get basic things done in
Many thanks for your post – saved me where the rest of t’internet failed!
David Murdock said,
Wrote on April 16, 2009 @ 11:45 am
Ben,
Thanks for the Post, It’s definitely explanatory of the basic process.
I have one question.
I would like to insert the value of a variable into the batchElement.InnerXML.
Such As:
batchElement.InnerXml = “”
“textbox4.Text”;
Can you please point me in the direction of how to accomplish this.
Thanks in Advance,
Dave
David Murdock said,
Wrote on April 16, 2009 @ 11:46 am
D’oh, looks like this blob page took out a bunch of the XML code when i submitted.
sweha said,
Wrote on April 17, 2009 @ 7:23 pm
When you insert a sharepoint list item from web services, can you also please show how to add attachments as well so that if i attach a file suppose in a webpage and hit submit, it shows up as an attachment in the sharepoint list for the inserted item.
I tried using listservice.AddAttachment(”listname”, “ID”, fileName, contents) but I don’t know how do I do it for ID where I don’t want to say “1″ or “2″ or “3″ as I am not trying to attach something to specifally item with id 1 or 2 or 3 in the list. I just want that whenever a new item is inserted, if it has an attachment, thn add that attachment also along with the other times in the list.
Ali raza said,
Wrote on June 24, 2009 @ 12:36 pm
i am stuck in one issue, if you can help me, iam using sharepoint List webservice to get attachement,
using method getAttachmentCollection,
It returns perfect attachement url on local machine, but when i publish the site to internet it return same url not the internet one, hostname does not change i tried to change the url using javascript relpace method but it does not work, can you please tell me how to fix this, i really have to finish this as soon as possible
calin said,
Wrote on July 30, 2009 @ 4:18 pm
Hi,
Thanks for the example. It seems I have to get used with all limitations provided by MS for SP developers. I’m wondering if it was easier for them to parse and interpret an XML instead of creating serializable business classes which could be manipulated through webservices and developers could achieve basic operations without having to read few hours on the internet about how the XML data should look like…
I guess I should say “Thanks again MS for keeping things complicated with SP”.