开发者

Sharepoint dynamic caml query problem?

开发者 https://www.devze.com 2022-12-15 00:31 出处:网络
I want to dynamic caml query based on query string.Let me explain it with example my query sting can be anything

I want to dynamic caml query based on query string.Let me explain it with example

my query sting can be anything

?cat=ABC&cat=ABD&cat=ABE...
?Cat=ABC
?Cat=ABC&cat=ABL开发者_如何学C

so no. can be anything now the problem begins

I want to query my sharepoint list based on this query string

if (HttpContext.Current.Request.QueryString["cat"] != null)
        {
            string _cat = HttpContext.Current.Request.QueryString["cat"].ToString();
        }

so this way my string contains all the query

string _cat=ABC,AD,....all.

I want to query my sharepoint list based on these query string and with "AND"

where title=ABC and title=AD ....

if there is only one query string then only where title=ABC....so I want my query string should be dynamic.... Any idea how to acheive this??


Assuming you are talking about a Multi-select choice field... most likely you will have to create the query each time.

Your code is going to need to determine how many categories are passed in and then generate the CAML. For example, if only ABC is passed your query would be (notice there are no <And> tags):

<Where>
  <Eq>
    <FieldRef Name='Category'/>
    <Value Type='Choice'>ABC</Value>
  </Eq>
</Where>

But if you have three choices passed in via QueryString: ABC, ABD, and ABE you would get (notice the <And> tags surround each group of two):

<Where>
  <And>
    <And>
      <Eq>
        <FieldRef Name='Category'/>
        <Value Type='Choice'>ABC</Value>
      </Eq>
      <Eq>
        <FieldRef Name='Category'/>
        <Value Type='Choice'>ABD</Value>
      </Eq>
    </And>
    <Eq>
      <FieldRef Name='Category'/>
      <Value Type='Choice'>ABE</Value>
    </Eq>
  </And>
</Where>

Edit:

static void Main(string[] args)
{
    try
    {
        string[] parameters = { "ABC", "DEF", "GHI" };
        string camlQuery = CreateCAMLQuery(parameters);
        Console.WriteLine(camlQuery);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    Console.WriteLine("Press any key...");
    Console.ReadKey();
}

private static string CreateCAMLQuery(string[] parameters)
{
    StringBuilder sb = new StringBuilder();

    if (parameters.Length == 0)
    {
        // perhaps set a default query?
        AppendEQ(sb, "all");
    }

    // "AND" each parameter to the query
    for (int i = 0; i < parameters.Length; i++)
    {
        AppendEQ(sb, parameters[i]);

        if (i > 0)
        {
            sb.Insert(0, "<And>");
            sb.Append("</And>");
        }
    }

    sb.Insert(0, "<Where>");
    sb.Append("</Where>");

    return sb.ToString();
}

private static void AppendEQ(StringBuilder sb, string value)
{
    // put your field's internal name in place of Category
    sb.Append("<Eq>");
    sb.Append("<FieldRef Name='Category'/>");
    sb.AppendFormat("<Value Type='Choice'>{0}</Value>", value);
    sb.Append("</Eq>");
}


check http://camlex.codeplex.com project. It was created exactly for simplifying of creation of dynamic CAML statements using C# lambda expressions. Also check my post: Build dynamic CAML queries based on query string parameters


I have developed C# code to build dynamic query. Its like this

 public string GenerateQuery(IList<CamlQueryElements> lstOfElement)
    {
        StringBuilder queryJoin = new StringBuilder();
        string query = @"<{0}><FieldRef Name='{1}' /><Value {2} Type='{3}'>{4}</Value></Eq>";
        if (lstOfElement.Count > 0)
        {
            int itemCount = 0;
            foreach (CamlQueryElements element in lstOfElement)
            {
                itemCount++;
                string date = string.Empty;
                // Display only Date
                if (String.Compare(element.FieldType, "DateTime", true) == 0)
                    date = "IncludeTimeValue='false'";
                queryJoin.AppendFormat(string.Format(query, element.ComparisonOperators,
                                element.FieldName, date, element.FieldType, element.FieldValue));

                if (itemCount >= 2)
                {
                    queryJoin.Insert(0, string.Format("<{0}>", element.LogicalJoin));
                    queryJoin.Append(string.Format("</{0}>", element.LogicalJoin));
                }
            }
            queryJoin.Insert(0, "<Where>");
            queryJoin.Append("</Where>");
        }
        return queryJoin.ToString();
    }

IList lstOfElement is custom object which holds filter elements. You can create your own object and pass into this method.


The basic algorithm for creating the CAML query string when you have multiple inputs is:

  • If there is only one value to check, you don't need the <And>, just create the code
  • If you have two values, you will need <and>(value1)(value2)</and>
  • If you have more than two, you create a loop (pseudocode, sorry):

    foreach (item in values)
     sQuery = "<And>" + sQuery + item + "</And>"
    end foreach
    


If you hate doing it using the String Concat method, You got to Try the JohnHolliday's Lib - CAML.NET, I use it in my project and it just rocks.

You too will love it

0

精彩评论

暂无评论...
验证码 换一张
取 消