Wednesday, November 20, 2013

Knockout JS with SharePoint 2010

1.      Create SharePoint webpart solution.
2.      Add Module to your project.
3.      Add Application page to module along with your Jquery-**.JS and Knockout-2.1.0.js file.
4.      Then add below code to your application page.aspx file.

<asp:Content ID="Content" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <script src="jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="jquery.tmpl.min.js" type="text/javascript"></script>
    <script src="knockout-2.1.0.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(function () {
            InitForm();
        });
        var viewModel;

        function InitForm()
        {
            $.getJSON('/_vti_bin/ListData.svc/MYTESTLIST',
                    function (data) {
                        viewModel = {
                            reports: ko.observableArray(data.d.results),
                            sortByName: function () {
                                this.items.sort(function (a, b) { return a.Title < b.Title ? -1 : 1; });
                            }
                        };
                        ko.applyBindings(viewModel);
                    });
        }
 </script>
    <script id='reportsRowTemplate' type='text/html'>
        <tr>
            <td><span data-bind='text:Id, uniqueName:true' /></td>
            <td><span data-bind='text:Title, uniqueName:true' /></td>
        </tr>
    </script>
     <p>You have <span data-bind='text: reports().length'> </span> report(s)</p>
     <table data-bind='visible: reports().length > 0'>
         <thead>
             <tr>
                 <th align=left>Report ID</th>
                 <th align=left>Report Name</th>
             </tr>
         </thead>
         <tbody data-bind='template: { name: "reportsRowTemplate", foreach: reports }' />
     </table>
     <button data-bind='click: sortByName, enable: reports().length > 0' type='submit'>Sort</button>
 </asp:Content>

Above example uses SharePoint web service and connect to  MYTESTLIST, it will fetch Title from the list and display it on the page.