I am quite new to Sharepoint and I am supposed to create a webpart that can display all the titles with a specific value from a managed metadata column(TAGS). I am required to write a CAML Query to probably return a list of documents that contains the TAGS value from the managed metadata column from a Document Library. Can I have some pointers to how am I supposed to deal with this? Thanks a lot :)
1 Answer
Below might help...Example is for Task list, but will work with any list type.
Suppose column name is ManagedMetadataColumn in you Task list and value you wanted to query by is 'My Value'
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
// Build a query.
SPQuery query = new SPQuery();
query.Query = string.Concat(
"<Where><Eq>",
"<FieldRef Name='ManagedMetadataColumn'/>",
"<Value Type='TaxonomyFieldType'>My Value</Value>",
"</Eq></Where>",
"<OrderBy>",
"<FieldRef Name='DueDate' Ascending='TRUE' />",
"<FieldRef Name=’Priority’ Ascending='TRUE' />",
"</OrderBy>");
query.ViewFields = string.Concat(
"<FieldRef Name='ManagedMetadataColumn' />",
"<FieldRef Name='LinkTitle' />",
"<FieldRef Name='DueDate' />",
"<FieldRef Name='Priority' />");
query.ViewFieldsOnly = true; // Fetch only the data that we need.
// Get data from a list.
string listUrl = web.ServerRelativeUrl + "/lists/tasks";
SPList list = web.GetList(listUrl);
SPListItemCollection items = list.GetItems(query);
// Print a report header.
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}",
"ManagedMetadataColumn", "Task", "Due Date", "Priority");
// Print the details.
foreach (SPListItem item in items)
{
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}",
item["AssignedTo"], item["LinkTitle"], item["DueDate"], item["Priority"]);
}
}
}
Console.ReadLine();
Hope this helps.... Happy coding!!!
-
// Get data from a list. string listUrl = web.ServerRelativeUrl + "/lists/tasks"; SPList list = web.GetList(listUrl); SPListItemCollection items = list.GetItems(query); So i can change this portion to a code where I retrieve data from my document library?A_B_C– A_B_C2019-05-14 04:50:41 +00:00Commented May 14, 2019 at 4:50
-
true....also change all the columns names according to your library.....Siddharth Vaghasia– Siddharth Vaghasia2019-05-14 04:59:55 +00:00Commented May 14, 2019 at 4:59
-
Noted sir, i will try. Do i implement these codes in my feature's event receiver or somewhere else?A_B_C– A_B_C2019-05-14 05:11:33 +00:00Commented May 14, 2019 at 5:11
-
You said you need this in custom Webpart right ? Above code is Sever object model..it will work anywhere if correct dll are being referredSiddharth Vaghasia– Siddharth Vaghasia2019-05-14 05:21:45 +00:00Commented May 14, 2019 at 5:21
-
Sir, so would u recommend me to put them in my webpart.xml , webpart.cs, or webpart.webpart file? Sorry i am really new to sharepoint especially webparts so do pardon my mistakes.A_B_C– A_B_C2019-05-14 05:26:59 +00:00Commented May 14, 2019 at 5:26