0
votes

I have a custom search webpart in Sharepoint which have 7 filters. I am getting data from a Sharepoint list using CAML Query. I want to write a generalized SPQuery which will filter out the data based on the search parameters. The search parameters are optional . If user enters any 2 parameters then I need to get data corresponding to those 2 parameters specified. How do I use CAML Query to achieve this? I am unable to think of a generalized approach for generating my caml query based on search parameters..

2
Can you give an example of what the input might look like? You'll need some logic between the parameters as well, what are the options you are allowing?Grace Note
I actually solved the issue by writing logic to dynamically generate the spqueryAbhishek Rao

2 Answers

1
votes

Here is a bit of code I used in Silverlight to generate a CAML query based on search parameters. Maybe it is helpful.

    private ClientContext context;
    private Microsoft.SharePoint.Client.List SampleSPList;
    private Microsoft.SharePoint.Client.ListItemCollection SampleSPCollection;

    //Load the List
    void LoadList()
    {
        SampleSPList = context.Web.Lists.GetByTitle("Sample");
        context.Load(SampleSPList);

        CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();

        string camlQueryXml = "";
        bool existsWhere = false;

        if (searchString.Text != "")
        {
            camlQueryXml = camlQueryXml + "<Contains><FieldRef Name='sampleString' /><Value Type='Text'>" + searchString.Text + "</Value></Contains>";
            if (existsWhere == true) {
                camlQueryXml = "<And>" + camlQueryXml + "</And>";
            }
            existsWhere = true;
        }

        if (searchTextArea.Text != "")
        {
            camlQueryXml = camlQueryXml + "<Contains><FieldRef Name='sampleTextArea' /><Value Type='Text'>" + searchTextArea.Text + "</Value></Contains>";
            if (existsWhere == true)
            {
                camlQueryXml = "<And>" + camlQueryXml + "</And>";
            }
            existsWhere = true;
        }

        if (existsWhere == true) { camlQueryXml = "<View><Query><OrderBy><FieldRef Name='ID' /></OrderBy><Where>" + camlQueryXml + "</Where></Query></View>"; }
        else { camlQueryXml = "<View><Query><OrderBy><FieldRef Name='ID' /></OrderBy></Query></View>"; }

        query.ViewXml = camlQueryXml;

        SampleSPCollection = SampleSPList.GetItems(query);
        context.Load(SampleSPCollection);
        context.ExecuteQueryAsync(ListLoaded, ListLoadFailed);
    }
0
votes

actually solved the issue by writing logic to dynamically generate the spquery