This article on retrieving List Attachment URLs and Document URLs is a continuation of series on Knockout Js with SharePoint 2013 REST API.
Handling both Document URLs and Attachment URLs are bit tricky in SharePoint 2013 REST API as the data is returned as nested Json Objects. KoSpJs eases this complexity of binding of SharePoint json data with html elements
To start with let us see how to retrieve and display URLs of documents from a document library
Document URLs
spHref and spAttr binders of KoSpJs can be used to bind document URLs. The below code snippet shows how to perform this. For this example I have created a document library named “Team Docs” and have drag and dropped a bunch of documents to it. I have also assigned values for “Title” field so that it can be showed as display text for hyperlinks rather than displaying the raw URLs
<div>
<table data-bind="template: { name: 'allDocs-template', foreach: Docs }" width="100%"></table>
</div>
<script type="text/html" id="allDocs-template">
<tr>
<td>
<a href="#" data-bind="spHref:$data,sourceType:'meta',displayField:'media_src'"></a>
</td>
<td>
<a href="#" data-bind="spHref:$data,sourceType:'meta',displayField:'media_src',displayText:Title"></a>
</td>
<td>
<a href="#" data-bind="spHref:$data,sourceType:'meta',displayField:'media_src',displayText:'Download Document'"></a>
</td>
<td>
<span data-bind="spAttr:$data,sourceType:'meta',displayField:'media_src',attrName:'title',displayText:Title"></span>
</td>
</tr>
</script>
<script type="text/javascript">
function DocsModal() {
var self = this;
self.Docs = ko.observableArray([]);
$.getJSON(_spPageContextInfo.webAbsoluteUrl + "/_vti_bin/listdata.svc/TeamDocs",
function (data) {
if (data.d.results) {
self.Docs(ko.toJS(data.d.results));
}
}
);
}
ko.applyBindings(new DocsModal());
</script>
Attachment URLs
spUrl binder of KoSpJs can be used to bind Attachment URLs from SharePoint List Attachments. The below code snippet shows how to bind attachment URL .This samples targets a custom list named “Doc Details”
<div id="docDetails">
<table data-bind="template: { name: 'allDocsDetails-template', foreach: DocsDetails }" width="50%"></table>
</div>
<script type="text/html" id="allDocsDetails-template">
<tr>
<td>
<div data-bind="spUrl:Attachments,multi:true, dataFormat:'<br/>'"></div>
</td>
<td>
<span data-bind="spUrl:Attachments,multi:true"></span>
</td>
</tr>
</script>
<script type="text/javascript">
function DocsDetailModal() {
var self = this;
self.DocsDetails = ko.observableArray([]);
$.getJSON(_spPageContextInfo.webAbsoluteUrl + "/_vti_bin/listdata.svc/DocDetails?$expand=Attachments",
function (data) {
if (data.d.results) {
self.DocsDetails(ko.toJS(data.d.results));
}
}
);
}
ko.applyBindings(new DocsDetailModal(),docDetails);
</script>
Leave a comment