SharePoint: The given key was not present in the dictionary.

This javascript error is encountered while working with External lists in 
SharePoint and using client side code to query the lists.While creating a query, if any of the fields from the external list is excluded from the ViewFields collection then this issue will occur.
For eample, I had an external list with four fields:
CustomerId, FirstName, LastName and Address
I wanted to get all First Names which contained alphabet "N" in them, so I created a query like this
'<View><Query><Where><Contains><FieldRef Name="FirstName"/><Value Type="Text">N</Value></Contains></Where></Query><View>'
but recieved above error, so I had to modify my query to this
'<View><Query><Where><Contains><FieldRef Name="FirstName"/><Value Type="Text">N</Value></Contains></Where></Query>' +
'<ViewFields><FieldRef Name="FirstName"/><FieldRef Name="CustomerId"/><FieldRef Name="LastName"/><FieldRef Name="Address"/></ViewFields></View>';
Here is a working example. Create a visual webpart in Visual Studio 2010 and copy the following 
code in .ascx file of the webpart.


<script src="/_layouts/SP.js" type="text/ecmascript">
</script>
<script type="text/javascript">
    var listName = "Customers";
    var clientContext = null;
    var web = null;

    function ViewItem() {
        clientContext = new SP.ClientContext.get_current();
        web = clientContext.get_web();
        var list = web.get_lists().getByTitle(listName);
        var camlQuery = new SP.CamlQuery();
        var query = '<View><Query><Where><Contains><FieldRef Name="FirstName"/><Value Type="Text">N</Value></Contains></Where></Query>' +
   '<ViewFields><FieldRef Name="FirstName"/><FieldRef Name="CustomerId"/><FieldRef Name="LastName"/><FieldRef Name="Address"/></ViewFields></View>';
        camlQuery.set_viewXml(query);
        this.listItems = list.getItems(camlQuery);
        clientContext.load(listItems);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess), Function.createDelegate(this, this.onQueryFailed));
    }

    function onListItemsLoadSuccess(sender, args) {
        var listEnumerator = this.listItems.getEnumerator();
        while (listEnumerator.moveNext()) {
            var item = listEnumerator.get_current();
            var title = item.get_item('FirstName');
            alert(title);
        }
    }
    function onQueryFailed(sender, args) {
        alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
    }
</script>

<a onclick="ViewItem();" href="#">View Items</a>

profile for Nadeem Yousuf at SharePoint Stack Exchange, Q&A for SharePoint enthusiasts

+