Udostępnij za pośrednictwem


How to: Get SPList based on the Internal Name from current SPWeb

While using JavaScript Object Model (ECMAScript) with SharePoint 2010, SP.ListCollection can be used to get SPList by using getById() or getByTitle(), however there is no such method to retrieve the list based on the list’s internal name. I found that SPList.RootFolder.Name is the nearest thing to internal name which SPListItem has. This will be required when site exists in different languages, hence lists are having different titles. So, what we can do here is to get all the lists and iterate over their rootfolder names and match with the desired list internal name. In this scenario we have to invoke executeQueryAsync multiple times.

Here is the code snippet:

 var ctx; function getListByInternalName(desiredListName) { this.desireableList = undefined; this.desireableListUrlName = desiredListName; ctx = SP.ClientContext.get_current(); this.web = ctx.get_web(); this.lists = web.get_lists(); ctx.load(this.lists); ctx.executeQueryAsync(Function.createDelegate(this, this.listsRetrievedSuccess), Function.createDelegate(this, this.listsRetrievedError)); } function listsRetrievedSuccess() { this.listEnumerator = lists.getEnumerator(); while (listEnumerator.moveNext()) { var list = listEnumerator.get_current(); var rootFolder = list.get_rootFolder(); ctx.load(rootFolder); } ctx.executeQueryAsync(Function.createDelegate(this, this.rootFoldersRetrievedSuccess), Function.createDelegate(this, this.rootFoldersRetrievedError)); } function listsRetrievedError() { } function rootFoldersRetrievedSuccess() { listEnumerator.reset(); while (listEnumerator.moveNext()) { var list = listEnumerator.get_current(); var rootFolder = list.get_rootFolder(); var name = rootFolder.get_name(); if (name == desireableListUrlName) { desireableList = list; break; } } if (desireableList !== undefined) { listFoundCallback(); } else { listNotFoundCallback(); } } function rootFoldersRetrievedError() { } function listFoundCallback() { console.log(desireableList.get_title()); } function listNotFoundCallback() { console.log("Matching list not found."); }

     We can use the above function by calling like this:

// list url: /MyCustomList getListByInternalName("MyCustomList");

 

 Happy Coding...!!!