Retrieving the content type of list items in a list item collection via JavaScript client object model

This took me a little while to work out – the documentation is pretty good but still requires a little bit of further exploration. I originally thought that you would require two service calls: one to get the list item collection, and then a second once the collection was available to be enumerated in the onSuccess callback. However, by using the Include method on the call to Load the list item collection we can make the content type available. This is demonstrated in the following code snippet.

function GetListItems() {

    var ctx = new SP.ClientContext.get_current();
    var list = ctx.get_web().get_lists().getByTitle('Test List');
    var query = new SP.CamlQuery();
    query.set_viewXml("<View><RowLimit>10</RowLimit></View>");
    items = list.getItems(query);
    ctx.load(items, 'Include(ContentType)');

    ctx.executeQueryAsync(onSuccess, onFailure);
}

/* Success callback */
function onSuccess() {
    var listEnumerator = items.getEnumerator();
    while (listEnumerator.moveNext()) {
        var currentItem = listEnumerator.get_current();
        var contentType = currentItem.get_contentType();
        var contentTypeName = contentType.get_name();
    }
}

/* Failure callback  */
function onFailure() {

}

Go on – give it a go!

This entry was posted in SharePoint 2010 and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>