将linq扩展到sharepoint以发布HTML字段

时间:2012-01-09 03:04:46

标签: c# sharepoint linq-to-sharepoint

我创建了一个部分类来扩展默认的spmetal类来处理发布html字段。如下所述:

Extending the Object-Relational Mapping

来自public partial class RelatedLinksItem : Item, ICustomMapping的片段:

/// <summary>
/// Read only data is retrieved in this method for each extended SPMetal field
/// Used to Read - CRUD operation performed by SPMetal
/// </summary>
/// <param name="listItem"></param>
[CustomMapping(Columns = new string[] { CONTENT_FIELDtesthtml, CONTENT_FIELDLink })]
public void MapFrom(object listItem)
{
    SPListItem item = (SPListItem)listItem;

    // link
    this.ContentLink = item[CONTENT_FIELDLink] as LinkFieldValue;

    // html (does NOT work)
    HtmlField html = item[CONTENT_FIELDtesthtml] as HtmlField; // this returns null

    // html (does work)
    HtmlField html2 = (HtmlField)item.Fields.GetFieldByInternalName(CONTENT_FIELDtesthtml); // this returns object
    this.Contenttesthtml = html2;
    this.TestHtml = html2.GetFieldValueAsText(item[CONTENT_FIELDtesthtml]); // set property for rendering html
}

来自“webpart”的片段:

    protected override void CreateChildControls()
    {
        using (OrganisationalPoliciesDataContext context = new OrganisationalPoliciesDataContext(SPContext.Current.Web.Url))
        {
            var results = from links in context.RelatedLinks
                          select links;

            foreach (var link in results)
            {
                // render link
                Controls.Add(new LiteralControl(string.Format("<p>Link: {0}</p>", link.ContentLink)));

                // render html
                Controls.Add(new LiteralControl(string.Format("<p>HTML: {0}</p>", link.TestHtml)));
            }
        }
    }

两个问题:

  1. 为什么HtmlField html = item[CONTENT_FIELDtesthtml] as HtmlField;会返回null,但item.Fields.GetFieldByInternalName正常工作?
  2. 有没有办法从内部使用GetFieldValueAsText方法 webpart或是将值存储在自定义中的方法 后来可以接受的财产?

1 个答案:

答案 0 :(得分:0)

  1. 您正在将item[CONTENT_FIELDtesthtml]的字段值转换为HtmlField类型。但HtmlField表示字段的类型,而不是字段值的类型。因此,HtmlField html将被分配null。请查看此MSDN page以获取所有发布字段类型和值类型的参考 我不确定HtmlField的字段值类型是什么。可能只是string 所以你应该可以安全地将其转换为字符串:

    string html = Convert.ToString(item[CONTENT_FIELDtesthtml]);
    
  2. 我认为将值存储在属性中是可行的方法。这样就可以实现数据层和表示层的分离。