0

How can I get the current view (the selected view) ID of a sharepoint list by using Javascript Object Model?

6

SharePoint 2010

Use ClientContext structure that is generated on the client-side and contains List View details:

//find active View Id
function getCurrentViewId(listId)
{
  var viewId;
  for(var ctxKey in g_ctxDict){
     var curCtx = g_ctxDict[ctxKey];
     if(curCtx.listName == listId){
        viewId = curCtx.view;
        break; 
     }
  }
  return viewId;
}  

var activeListId = SP.ListOperation.Selection.getSelectedList();
var activeViewId = getCurrentViewId(activeListId);
getListView(activeListId,activeViewId, 
       function(view){
         console.log(view.get_title());
       },
       function(sendera,args){
         console.log(args.get_message());
     });

SharePoint 2013

In addition to capabilities available in SharePoint 2010, you could consider the following approach.

Use SP.ListOperation.ViewOperation.getSelectedView() method or SP.ListOperation.Selection.getSelectedView() method from SP.ListOperation namespace to retrieve active View Id, the following example demonstrates how to retrieve View details:

var activeListId = SP.ListOperation.Selection.getSelectedList();
var activeViewId = SP.ListOperation.ViewOperation.getSelectedView();

getListView(activeListId,activeViewId, 
   function(view){
       console.log(view.get_title());
   },
   function(sendera,args){
       console.log(args.get_message());
   });

How to get View using SharePoint JSOM

function getListView(listId,viewId,success,error)
{
   var ctx = SP.ClientContext.get_current();
   var list = ctx.get_web().get_lists().getById(listId);
   var view = list.get_views().getById(viewId);
   ctx.load(view);
   ctx.executeQueryAsync(
      function() {
          success(view); 
      },
      error);
}
  • 1
    Great answer. FYI, I am on SP 2013 and I found that g_ctxDict doesn't contain anything inside it in a page containing list view webpart. The length of the dictionary is zero. – Nadeem Yousuf Dec 17 '14 at 14:31
  • Thanks, Nadeem! Regarding SharePoint 2013, hmm.. i could access it, probably the length is because it is not an array but an object(!), you could try to see it's content like this: console.log(g_ctxDict) ;) – Vadim Gremyachev Dec 17 '14 at 15:18
  • 1
    This guy always give great answers with the details. Like you :) – tbbt Dec 18 '14 at 3:29
  • hi guy, var activeViewId = SP.ListOperation.ViewOperation.getSelectedView(); sometime doesn't work? – tbbt Dec 18 '14 at 4:50
  • The SP.ListOperation only works when the items of list is selected. Are there any ways without selecting the item? – tbbt Dec 18 '14 at 6:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.