Wednesday, October 16, 2013

SharePoint 2013: Creating a New List Item Using the Client-Side Object Model (CSOM)

I have been working on a provider-hosted app for SharePoint 2013 which needs to create lists and add some default items if they do not exist. I therefore am using the client-side object model (CSOM) in order to accomplish this.

It seemed like everything was spelled out for me on this MSDN post: http://msdn.microsoft.com/en-us/library/fp179912.aspx

However, when attempting to access the Items collection on the list, I received an error:


'Microsoft.SharePoint.Client.List' does not contain a definition for 'Items' and no extension method 'Items' accepting a first argument of type 'Microsoft.SharePoint.Client.List' could be found (are you missing a using directive or an assembly reference?)


I thought I was in trouble but then I noticed that the List object had an AddItem method. So pretty simple fix, I just needed to change my syntax from list.Items.Add to just list.AddItem:


This worked like a charm.

The corrected full example  should therefore be:

// Starting with ClientContext, the constructor requires a URL to the
// server running SharePoint.
ClientContext context = new ClientContext("http://SiteUrl");

// Assume that the web has a list named "Announcements".
List announcementsList = context.Web.Lists.GetByTitle("Announcements");

// We are just creating a regular list item, so we don't need to
// set any properties. If we wanted to create a new folder, for
// example, we would have to set properties such as
// UnderlyingObjectType to FileSystemObjectType.Folder.
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newItem = announcementsList.AddItem(itemCreateInfo);
newItem["Title"] = "My New Item!";
newItem["Body"] = "Hello World!";
newItem.Update();

context.ExecuteQuery(); 


 

No comments:

Post a Comment

Matched Content