13

When using CAML to extract from a list, what is the purpose of the viewfields in the query - to set value types - text, interger,etc. - and make the fields available so the get_item('fieldname') method can pull the data from them? If the viewfields is omitted can you use the get_item('fieldname') method?

3 Answers 3

13

<ViewFields> is used in the CAML query to define that how many fields you want to retrieve by executing the query. If we did not define <ViewFields> then it will retrieve all the columns of list.

For example if I define ViewFields like:

<ViewFields>
    <FieldRef Name="ID"></FieldRef>
    <FieldRef Name="Title"></FieldRef>
</ViewFields>

then it will retreive only two columns ID & Titile from the list.

It's not mandatory to set <ViewFields>.

Read more: SPQuery.ViewFields Property

5
  • Are you saying that since only the two fields are being retrieved these are the only two fields that the get_item method will display - get_item(departmentname') would not return anything?
    – PianoMan
    May 28, 2016 at 5:06
  • Yes, it will retrieve only those fields which are defined in ViewFields. To get the 'departmentname' field you have to include that field in ViewFields like <FieldRef Name="departmentname"></FieldRef> May 30, 2016 at 4:31
  • Thanks. I'm using JS so your link was much help but appreciated.
    – PianoMan
    Jun 9, 2016 at 1:33
  • Welcomes .. :) @PianoMan Jun 9, 2016 at 4:00
  • This doesn't work if the field is empty.
    – Batman
    Aug 12, 2016 at 4:15
7
  • ViewFields basically gives you option to reduce data in response.
  • It allows you to specify which fields you want in return for your query.

It is always a best practice to use ViewFields as and when possible.

Also in conjunction with SPQuery.ViewFields you must use SPQuery.ViewFieldsOnly, then only it will return only those column, else it is going to return all column in response.

For Ex:

SPQuery query = new SPQuery();

query.Query = <<YOUR QUERY GOES HERE>>
query.ViewFields = "<ViewFields>"+
    "<FieldRef Name="ID"></FieldRef>"+
    "<FieldRef Name="Title"></FieldRef>"+
"</ViewFields>";

query.ViewFieldsOnly = true; 
2
  • Are you saying that in addition to the fields requested by viewfieilds ALL the fields are available to the get_item('fieldname') method? I like the idea of using the only feature. I have never seen that appear in any of the examples I have come across. I'll have to look into that. Thanks
    – PianoMan
    May 28, 2016 at 5:11
  • sure @PianoMan . I hope you must have tried it by now
    – Gaurravs
    Nov 21, 2018 at 4:26
1

In the list views, Viewfields are essentially the columns that you see in the list view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.