SharePoint CSOM List
client object exposes List.AddItem method to create a new list item in the list:
public ListItem AddItem(
ListItemCreationInformation parameters
)
Since CSOM
is asynchronous, two approaches are commonly used when it comes to make CSOM code maintainable:
Callback approach
function AddListItem(listTitle,itemProps,OnItemAdded,OnItemError)
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var itemCreateInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemCreateInfo);
for(var propName in itemProps) {
listItem.set_item(propName, itemProps[propName])
}
listItem.update();
context.load(listItem);
context.executeQueryAsync(
function() {
OnItemAdded(listItem);
},
OnItemError
);
}
Usage
AddListItem('Contacts',contactEntry,
function(contactItem){
console.log('Contact ' + contactItem.get_item('Title') + ' has been created successfully');
},
function(sender,args){
console.log('Error occured while creating contact:' + args.get_message());
});
Deferred approach
A deferred - is a pattern that returns an object immediately from an
asynchronous call
function AddListItemD(listTitle,itemProps)
{
var dfd = $.Deferred(function () {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var itemCreateInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemCreateInfo);
for(var propName in itemProps) {
listItem.set_item(propName, itemProps[propName])
}
listItem.update();
context.load(listItem);
context.executeQueryAsync(
function () {
dfd.resolve(listItem);
},
function (sender, args) {
dfd.reject(args.get_message());
}
);
});
return dfd.promise();
}
Usage
AddListItemD('Contacts',contactEntry).then(function(contactItem){
console.log('Contact ' + contactItem.get_item('Title') + ' has been created successfully');
});
Since SP.SOD.executeFunc
supports on demand scripts, but SP.SOD.executeOrDelayUntilScriptLoaded
does not, I would recommend to use SP.SOD.executeFunc
with CSOM in application pages:
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
var clientContext = SP.ClientContext.get_current();
});