Wednesday, 15 July 2015

Programmatically getting the values from a SharePoint list view

Hi,
 Today I will share the code for getting the values of the items in a particular view through Client Side Object Model.
For this we have to make 2 requests. First request is to get to know which view & view query and second would be for getting the values from that view.

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItemsFromView);
});

// First request
function getItemsFromView()
{
    var context = new SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle('List Name');
    var view = list.get_views().getByTitle('View Name');
    context.load(view);
    context.executeQueryAsync(
        function (sender, args) { getItemsFromList('List Name', "<View><Query>" + view.get_viewQuery() + "</Query></View>") },
        function(sender, args) {alert("error: " + args.get_message());}
    );
}
//Second Request
function getItemsFromList(listTitle, queryText) {
    var context = new SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle(listTitle);
    var query = new SP.CamlQuery();
    query.set_viewXml(queryText);
    var items = list.getItems(query);
    context.load(items);
    context.executeQueryAsync(
        function () {
            var listItemInfo = '';
            var listEnumerator = items.getEnumerator();
            var i = 0;
            while (listEnumerator.moveNext())
            {
                i++;
            }
            alert("items retrieved: " + i);
         
        },
     
function (sender, args) { alert("error in inner request: " + args.get_message()); }
   );
}

Hope this helps. Happy Coding :)

No comments:

Post a Comment