Using ListData service in SharePoint 2010

For the past few weeks, I have been using ListData.svc, SharePoint Client object model and Jquery to create custom web parts which display some information from a list. First things first, ListData service reside in http:///_vti_bin/ListData.svc. So as an example, Let’s say that I have an employee list with First Name and Last Name columns. In order for me to get the list of employees from Employee list, the url would be http://samplesite/_vti_bin/ListData.svc/Employee.


var listUrl = 'http://samplesite/_vti_bin/ListData.svc/Employee';
$.getJSON(listUrl, function(data) {
   for (var i=0; i<data.d.results.length; i++)
   {
       var employee = data.d.results[i];
       alert(employee.FirstName);
   }
});

We can also filter the results that we would like to retrieve from the list by using the $filter query string or sort the results by using the $orderby. The example below filters the list by using the list item Id. For more information on what query strings that can be used, please have a look at this page in MSDN.

var listUrl = 'http://samplesite/_vti_bin/ListData.svc/Employee?$filter=Id eq 15';
$.getJSON(listUrl, function(data) {
   for (var i=0; i<data.d.results.length; i++)
   {       
   }
});

We can also use ListData service to create a new list item or update an existing item. Credits go to Anatoly Mironov for explaining on how to perform save and update operations. Following our example above, let’s say that we want to create an entry for a new employee

var newEmp = {};
newEmp.FirstName = "Joe";
newEmp.LastName = "Blogg";

var body = Sys.Serialization.JavaScriptSerializer.serialize(newEmp);

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            processData: false,
            url: listUrl,
            data: body,
            dataType: "json",
            success: function () { alert('succeeded');},
            error: function (xhr, status, error) { alert(xhr.responseText); }
        });
    }

Assuming that the create operation above succeeded and the new employee’s id is 20. We can update the employee list item as such

var emp = {};
emp.FirstName = "Joe";
emp.LastName = "B";

var body = Sys.Serialization.JavaScriptSerializer.serialize(emp);
$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            processData: false,
            headers: {
                "If-Match": "*",
                "X-HTTP-Method": "MERGE"
            },
            url: listUrl + "(20)",
            data: body,
            dataType: "json",
            success: function () { alert('succeeded');},
            error: function (xhr, status, error) { alert(xhr.responseText); }
        });

Notice the url and the headers for the AJAX call. The url that I specified points to the record that I just created and then I specified ‘MERGE’ to indicate that this is an update operation.

Retrieving SP user info using Client Object Model

Recently I built a visual web part to show current user’s information (Picture, Name, etc). Instead of using SharePoint server object model, this time I choose to use client OM. First I need to get the id of the logged-in user, which can be retrieved from _spPageContextInfo.userId (Ted Pattison has posted an excellent article explaining this variable). Next step is to get the client context.

var context = new SP.ClientContext.get_current();
    var web = context.get_web();

    var userInfoList = web.get_siteUserInfoList();

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\' />' +
                                '<Value Type=\'Number\'>' + userId + '</Value></Eq>' +
                                '</Where></Query><RowLimit>1</RowLimit></View>');

    this.userListItem = userInfoList.getItems(camlQuery);

    context.load(this.userListItem);

    context.executeQueryAsync(
            Function.createDelegate(this, onSucceeded),
            Function.createDelegate(this, onFailed));

The onSucceeded function is called when the query runs successfully, otherwise the onFailed function will be executed.


function onSuceeded(sender, eventArgs)
{
        var item = this.userListItem.itemAt(0);
        var name = item.get_item('Name');
        var userName = "Name";

        if (name) {
            userName = name;
        }

        alert(userName);
}

One last thing to remember is to run the code after SP.js is loaded

SP.SOD.executeOrDelayUntilScriptLoaded(LoadUserInfo, 'SP.js');

Using JsRender to render HTML template

I just happened to use jsrender on my recent project and I have to say that it really helps to simplify my code. jsrender is a javascript templating engine which is used for string based rendering.

For example, let’s say I want to show new employees as below:

So the first thing to do is to get the list of employees as JSON, then I can use JavaScript to manipulate DOM. I could write the following Javascript (which is a bit complicated):

First, the sample data


var employees = [
                                {
                                    Name: "Joe Blogg",
                                    Role: "Software Developer",
                                    Email: "jblogg@email.com"
                                },
                                {
                                    Name: "Jill Blogg",
                                    Role: "Marketing Officer"                                    
                                },
                                {
                                    Name: "Jack Blogg",
                                    Role: "Project Manager",
                                    Email: "jblogg@email.com"
                                },
                                {
                                    Name: "Jon Blogg",
                                    Role: "Software Developer",
                                    Email: "jblogg@email.com"
                                },
                                {
                                    Name: "James Blogg",
                                    Role: "Software Developer"                                    
                                }
            ];

The JavaScript:

var content;
$(employees).each(function (val) {
  content = "<li><ul><li class='innerList'>" + val.Name + "</li>"
              + "<li class='innerList'>" + val.Role + "</li>"
              + "<li class='innerList'>" + val.Email + "</li>"
              + "</ul></li>"
});

$("#dvContainer ul").append(content);

The JavaScript above can get harder to read as the content grows. So let’s look at the jsrender version:

<script id="ViewTemplate" type="text/x-jsrender">    
            
            <li class="outerList">                 
                <ul>
                    <li class="innerList">{{>Name}}</li>
                    <li class="innerList">{{>Role}}</li>
                    <li class="innerList">{{if Email}} {{>Email}} {{else}} ??? {{/if}}</li>
                </ul>                               
            </li>             
    </script>

<script type='text/javascript'>
$("#dvContainer ul").append($("#ViewTemplate").render(employees));
</script>

The jsrender version above uses template which is wrapped in a script tag (there is another way to define the template which can be found on the jsrender site above). The template defines how the data should be displayed. Once we have done the template, we can use the render() function to generate a string that is ready to be inserted to DOM. The {{>}} is jsrender syntax to encode the value.

Please note that you can use jsrender without jquery.

The code for this post can be found in here