SharePoint 2013 如何使用TaxonomyWebTaggingControl 控件

时间:2023-03-09 19:13:07
SharePoint 2013 如何使用TaxonomyWebTaggingControl 控件

  在该文章中,我将介绍如何使用TaxonomyWebTaggingControl控件, 首先我相信您已经在SharePoint Managed Metadata Service里定义Term Sets,如果没有,请先定义您的Term Sets(可以参考该文章how to create metadata column), 该控件能帮助我们显示/设置各种Terms。

  其次我们需要了解Managed Metadata的结构,请看以下图,您可以清晰地看到每一个结构(Term Store -> Group -> Term Set -> Terms),接下来我们进入主题, 该如何使用TaxonomyWebTaggingControl 控件绑定这些数据呢,在该案例中我们绑定Product Type Group的所有数据。

SharePoint 2013 如何使用TaxonomyWebTaggingControl 控件

  根据以下步骤:

  1. 在我们的设计页面中定义注册Microsoft.SharePoint.Taxonomy控件
<%@ Register TagPrefix="Taxonomy" Namespace="Microsoft.SharePoint.Taxonomy" Assembly="Microsoft.SharePoint.Taxonomy, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

  2.  在内容部分添加TaxonomyWebTaggingControl控件

<Taxonomy:TaxonomyWebTaggingControl ID="twtc_productType" runat="server"></Taxonomy:TaxonomyWebTaggingControl>

  3.  在后台绑定数据(从Managed Metadata Service中获取Group的数据)

  

 using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy; /// <summary>
/// TaxonomyWebTaggingControl Bind
/// </summary>
/// <param name="productTypeControl">TaxonomyWebTaggingControl Control</param>
public static void ProductTypeBind(TaxonomyWebTaggingControl productTypeControl)
{
// Open the site
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
TaxonomySession session = new TaxonomySession(site);
// Get the Term Store node from Managed Metadata Service
TermStore termStore = null;
if (session.TermStores != null && session.TermStores.Count > )
{
termStore = session.TermStores["Managed Metadata Service"]; //if you a custom meta service you should change name.
}
if (termStore != null)
{
//Guid anchorId = new Guid();
Group group = termStore.Groups["Product Type"]; // Get the Group node from Managed Metadata Service
productTypeControl.SspId.Add(termStore.Id); // do it for all termsets
foreach (TermSet item in group.TermSets)
{
productTypeControl.TermSetId.Add(item.Id); // Add the Term
/* This could be achieved by setting AnchorId property for TaxonomyWebTaggingControl control that allows to specify ID of parent Term for any valid value in control.
foreach (Term term in item.Terms)
{
if (term.Name == ManagedMetadataType.TermName)
{
anchorId = term.Id;
break;
}
} */
} //productTypeControl.AnchorId = anchorId;
productTypeControl.GroupId = group.Id;
productTypeControl.IsAddTerms = false;
}
}
}
}

  以上代码将可以获取Product Type(defined by GB/T 13702-1992)节点的数据, 可以查看一下效果图

SharePoint 2013 如何使用TaxonomyWebTaggingControl 控件

  有些朋友会问是否可以根据Term 节点作为父节点显示?对于该问题的回答是可以, 比如我想以All为父节点,我们仅仅通过该控件中的AnchorId属性,将All的id赋值给AnchorId即可,留心的朋友会发现在以上代码中注释部分就是实现该功能

  SharePoint 2013 如何使用TaxonomyWebTaggingControl 控件

  如果有大牛认为有更好的idea, 请提供您宝贵的建议供大家学习,谢谢