Get View collection from SharePoint List

This post explains, how to get the view and its details from SharePoint List using PnP JavaScript Library.

In this article, we will cover how to use the PnP JS Core library to get the collection of views from the SharePoint List. To know more about this JavaScript library, check the below links

In this post,

How to get collection of views from List using PnP JavaScript Library.

Syntax:

pnp.sp.web.lists.getByTitle(<ListName>).views 
Returns the collection of views from the list specified in the ListName parameter

Example:

The below steps and code snippets used to get a view details from the list using PnP JavaScript library,

  1. Download Required files to use PnP-JS-Core library from the below links and upload that to Site Asstes or Style Library
    • Download pnp.js  PnP JS file
    • Download fetch.js Used by PnP js file to handle web requests and responses (Required in IE)
    • Download promise.js Used by PnP js file to handle web requests and responses (Required in IE)
  2. Create new web part page and insert Content Editor web part
  3. Create a sample.html file in Site Assets or Style library and insert the below code snippet

[code lang=”js”]

<script type="text/javascript" src="/siteassets/scripts/fetch.js"></script>
<script type="text/javascript" src="/siteassets/scripts/promise.min.js"></script>
<script type="text/javascript" src="/siteassets/scripts/pnp.min.js"></script>

<span id="sample"></span>

<script type="text/javascript">
//The below views property returns the collection List Views
$pnp.sp.web.lists.getByTitle("CustomList").views.get().then(function(res) {
var strHtml = "";
for (var i = 0; i < res.length; i++) {
strHtml += "<strong>" + res[i].Title + "</strong><br/>";
strHtml += "ID: " + res[i].Id + "<br/>";
strHtml += "URL: " + res[i].ServerRelativeUrl + "<br/>";
}
document.getElementById("sample").innerHTML = strHtml;
});
</script>

[/code]

Typescript Example:

Typescript is the superset of JavaScript and this PnP JS library is developed using the typescript specification. For developing the SharePoint Framework web parts and make the client side development easier, we can vote for typescript. The below is the typescript example for retrieving the list views.

[code lang=”js”]

import pnp from "sp-pnp-js";

pnp.sp.web.lists.getByTitle("CustomList").views.get().then((res) => {
let strHtml: string = "";
for (let view of res) {
strHtml += "<strong>" + view.Title + "</strong><br/>";
strHtml += "ID: " + view.Id + "<br/>";
strHtml += "URL: " + view.ServerRelativeUrl + "<br/>";
}
document.getElementById("sample").innerHTML = strHtml;
});
[/code]

Output:

All Items
ID: ca0ac4cf-e1b4-4b20-8058-f982c8608152
URL: /Lists/CustomList/AllItems.aspx
My Items
ID: 0f0e622d-3cbd-42fb-a11d-2124152791cf
URL: /Lists/CustomList/MyItems.aspx
Shantha Kumar
Shantha Kumar
Articles: 277