ClientContext + camlQuery.ViewXml
-
16-10-2019 - |
Question
I use SP Client and want to return ListItemCollection which will be filled with items from specific view which I choose. I get ViewQuery string by sending view index in viewcollection. Problem is in part where I send camlQuery to GetItems method "ListItemCollection listItems = list.GetItems(camlQuery);" because whatever camlquery is sent to GetItems I allways get ALL items from list instead of FILTERED ones, despite the fact that camlquery string are good and different every time. Any suggestion?
clientContext.ExecuteQuery();
List list = site.Lists.GetByTitle(SPList);
clientContext.Load(list);
clientContext.ExecuteQuery();
ViewCollection viewItems = list.Views;
clientContext.Load(viewItems);
clientContext.ExecuteQuery();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = list.Views[index].ViewQuery;
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
Solution
I've had this recently.
The Client OM version of CamlQuery behaves differently to how you think.
Inspect the results of list.Views[0].ViewQuery.
If it has a tag around it, remove it before you assign to it CamlQuery.ViewXml. (possibly a bit tricky)
If it doesn't have a tag around it, add one. (easy)
Then assign it to CamlQuery.ViewXml. Almost certain this will work, as the symptoms you describe are identical to what I had, except I was using the Silverlight object model. Same objects, however.
EDIT:
Also, streamline your code, you've got a lot of "blocking" operations there that you probably don't need...
clientContext.ExecuteQuery();
List list = site.Lists.GetByTitle(SPList);
ViewCollection viewItems = list.Views;
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = list.Views[index].ViewQuery;
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(list);
clientContext.Load(viewItems);
clientContext.Load(listItems);
clientContext.ExecuteQuery();