SharePoint versions prior to 2010 have been using SharePoint API (a.k.a. Server-Side Object model) to develop SharePoint web parts. Although the API allowed CRUD operations on SharePoint data, the restriction was that it had to be run on the SharePoint server or a developer would alternatively use SharePoint's web server interface, which had its own limitations from a design perspective.
With SharePoint 2010, developers were now able to use Client Side Object Model to develop Web parts. The Client Side Object Model is a subset of the SharePoint API which mimics a large portion of the server-side API. The advantage of the client-side API is it can be called from .NET apps, Silverlight or using JavaScript libraries. In SharePoint 2013, the client-side API has been extended with REST/OData endpoints.
This article is published from the DotNetCurry .NET Magazine – A Free High Quality Digital Magazine for .NET professionals published once every two months. Subscribe to this eMagazine for Free and get access to hundreds of free tutorials from experts
In this article, we will learn how to make use of JavaScript libraries to fetch data from SharePoint List and bind that data to some controls using SharePoint Web parts. For this demonstration, we will make use of AngularJS and KnockoutJS JavaScript libraries.
A Quick Look into AngularJS and KnockoutJS
Before getting started, let’s quickly introduce the two JavaScript libraries – Angular JS and Knockout JS.
AngularJS
AngularJS is an open source MV* JavaScript framework maintained by Google and community, for building rich, interactive, single page applications (SPA). AngularJS uses HTML as your template language and lets you extends the HTML vocabulary for your application. The * in AngularJS represents MVC, MVVM or the MVP pattern which makes both development and testing of AngularJS applications easier. The main components of AngularJS are shown here –
Controller – Controller is key to AngularJS. A Controller is a JavaScript constructor function that is used to create a scope. A controller is attached to the DOM via ng-controller directive. You can use controllers to initiate the state of the $scope object and add behaviours to $scope object. $scope – is a glue between a Controller and DOM and just watches the changes to models and also applies changes to the model. One thing to note about Controller is they do not perform DOM manipulations or maintain state. AngularJS uses Services to maintain state.
Services – Services are used to perform common tasks on the web applications which are consumed by Angular JS via Dependency Injection. Services are registered with a Module and are usually singular to the application.
Views – Views are complied DOM of Angular JS. A view is produced using $compile with HTML templates and $scope.
With clientside implementation, Angular can have integration with the server using REST and $http service.
KnockoutJS
KnockoutJS is a fantastic library when you are looking for a drop-in enhancement that brings in client side data-binding and applies the Model-View-View-Model design pattern to your websites.
Knockout works with a ViewModel that can either be a JS object or a JS function. Either ways, your ViewModel is your data source. Using Knockout, you can bind DOM elements to your model using a declarative syntax. Knockout also provides Templating (for repetitive structures in a web page) and dependency tracking using ko.observableArray. With dependency tracking, if a property is changed, it will automatically notify the UI. The UI reflects these changes and can also change the value to automatically update the source object again.
This was just a small introduction of Angular JS and Knockout JS libraries. We can get more details on both the libraries here –
- Angularjs.org
- Knockoutjs.com
You can also learn more about AngularJS in Getting Started with AngularJS in ASP.NET MVC and about Knockout at Getting Started with KnockoutJS in ASP.NET MVC
Using AngularJS and KnockoutJS in SharePoint
Using these libraries in SharePoint development can make a big difference as we will see shortly. We will use these libraries with SharePoint Web parts using our very favorite tool – Microsoft Visual Studio. I am using Visual Studio 2013 for these demonstrations.
I have already created a SharePoint Site using Team site Template –
We will create a Custom List in our SharePoint site with the name Customers and some columns as described here –
- CustomerID
- ContactName [Rename title column]
- City
- Country
- ContactNo
Add some default data in our customers list. The list should look like the following –
Before we start building the Web Part, we will query SharePoint list data using OData queries. Let’s write some queries in our browser as described here –
· http://localhost/sites/dncmag/_api/web/lists/getByTitle('Customers')/items
· http://localhost/sites/dncmag/_api/web/lists/getByTitle('Customers')/items?$select=CustomerID,Title,City,Country,ContactNo
The output of the above query which uses $select operator is as shown –
As already mentioned earlier, we will be using Visual Studio to build our Web Part using the AngularJS library. Before that, we will need to add the scripts into our /_layouts/15/Scripts folder. Go to Windows Explorer and browse the following path –
C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS
Now create a Scripts folder under Layouts folder and add the following script files into the same –
I will also be using Twitter Bootstrap to make my UI look better. To those new to Bootstrap, it is a package that consists of predefined CSS styles, Components and jQuery plugins. It is licensed under Apache 2.0 and is free for commercial use. I have added the Bootstrap CSS into Scripts folder, although ideally you should create a separate CSS folder if you will be dealing with too many CSS files.
Also add some empty JavaScript files with the names SharePointListModule.js and CustomerController.js in the Scripts folder. We will these two files when we will be writing the script for fetching the SharePoint List Data using Angular JS.
Now we are ready to build the SharePoint Visual Web Part using AngularJS. Open Visual Studio and create a New Project. Choose Office/SharePoint > SharePoint Solutions and choose SharePoint 2013 – Visual Web Part template as shown here –
Click on the OK button. This will now show you a dialog box which will ask you for a site URL and security level for debugging.
Once the Web Part project is created, we will first import the AngularJS, Bootstrap JS, Bootstrap CSS, SharePointListModule.js and CustomerController.js in our User Control as shown here –
Now we will create an Angular Module. You can think of a module as a container which wires the different parts of your application like controllers, services, directives, etc. To create an Angular Module, write the following code in our SharePointListModule.js file –
We will now add a Controller which will fetch the data from our SharePoint List using $http service. We will use the SharePoint OData query and bind the data in our user control. Let’s write some code in CustomerController.js file as shown here –
var webSiteURL = "<%= SPContext.Current.Web.Url %>";
myAngApp.controller('spCustomerController', function ($scope, $http) {
$http({
method: 'GET',
url: webSiteURL + "/_api/web/lists/getByTitle('Customers')/items?$select=CustomerID,Title,City,Country,ContactNo",
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (d, s, h, c) {
$scope.customers = d.d.results;
});
});
In the script we just saw, we have first created an Angular Controller with the name ‘spCustomerController’. We have also injected $scope and $http service. The $http service will fetch the list data from the specific columns of SharePoint list. $scope is a glue between Controller and a View. It acts as execution context for Expressions. Angular expressions are code snippets that are usually placed in bindings such as {{ expression }}.
You might have observed that we are creating separate JavaScript files for creating Angular JS Module and Controller. As already mentioned, the AngularJS module acts as a container for Controllers, Services, Filters, and Directives etc. Modules declaratively specify how an application should be bootstrapped. It offers several advantages like –
- The declarative process is easier to understand
- Modules can be reusable
- Modules can be loaded in any order or parallel
- Unit testing and end-to-end testing is easier
We will now build the UI which will display SharePoint list data in our User Control. Let’s write the following code after the script –
Customer ID |
Contact Name |
City |
Country |
Contact No |
---|
{{customer.CustomerID}} |
{{customer.Title}} |
{{customer.City}} |
{{customer.Country}} |
{{customer.ContactNo}} |
In above HTML, we are using table and ng-repeat to iterate through the customers. Now deploy the Web Part and add the same in your SharePoint site. You should see the following output –
Using KnockoutJS in SharePoint
We will repeat the same demonstration that we did earlier with AngularJS, now using KnockoutJS. We will create one more webpart, but this time we will go with KnockoutJS JavaScript library to bind the data in our User Control. Before creating the Web Part, let’s add the following class libraries into our Script folder –
- jquery-2.1.0.min.js
- knockout-3.1.0.js
Follow the same steps to create a Web Part using Visual Studio as described in AngularJS Web Part section. Once the Web Part is created, we will now add the references of script files into our User Control as shown here –
To fetch the data from SharePoint list [Customers], we will make use of jQuery AJAX. Let’s write the following script in our user control –
Note: I am using the success() function considering those who are still using jQuery 1.7 or earlier. If you are using the latest version of jQuery, replace success() with done().
The above script, fetches the data from SharePoint List and exposes it as a Knockout observable array. We will now build the UI for our user control in which we will use the KnockoutJS binding capabilities. Let’s write some code in our User Control after the script
WelCome To Knockout JS Web Part !!
Customer ID |
Contact Name |
City |
Country |
Contact No |
---|
|
|
|
|
|
In the above HTML, we are using Knockout JS foreach loop to iterate through the list of customers. Now build the Web Part and deploy it to a SharePoint site. After deployment, add the Web Part on SharePoint site and the output should be similar to the following –
There you go! You now have a number of possibilities open to build different SharePoint Applications like Web Parts or SharePoint Apps.
Summary – In this article, we saw how you can use the client side JavaScript libraries like Angular JS and Knockout JS in SharePoint.
Download the entire source code of this article (Github)
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Pravinkumar, works as a freelance trainer and consultant on Microsoft Technologies. He is having over 10 years of experience in IT and is also a Microsoft Certified Trainer(MCT). He has conducted various corporate trainings on all versions of .NET Technologies including .NET, SharePoint Server, Microsoft SQL Server, Silverlight, ASP.NET, Microsoft PerformancePoint Server 2007 (Monitoring). He is passionate about learning new technologies from Microsoft. You can contact Pravinkumar at dabade[dot]pravinkumar [attherate] gmail[dot]com