以编程方式使用递归获取文档库的子项

时间:2013-01-21 09:44:48

标签: sharepoint recursion sharepoint-2010 sharepointdocumentlibrary

我需要通过文档库的内容进行递归,并使用MVC在网页上显示它们。但是,在尝试运行我的代码时出现以下错误:“集合尚未初始化。尚未请求或请求尚未执行。可能需要明确请求。”

任何帮助将不胜感激!

这是我的代码:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            DefaultModel model = new DefaultModel();


            using (ClientContext context = new ClientContext("MySPSite"))
            {
                List list = context.Web.Lists.GetByTitle("DocumentLibrary");
                Folder rootFolder = list.RootFolder;

                IEnumerable<SharePointItemBaseModel> items = ProcessFolder(rootFolder);
                model.items.AddRange(items);
            }

            return View(model);
        }

        public IEnumerable<SharePointItemBaseModel> ProcessFolder(Folder folder)
        {
            List<SharePointItemBaseModel> listItems = new List<SharePointItemBaseModel>();
            foreach (Folder childFolder in folder.Folders)
            {
                FolderModel folderModel = new FolderModel();
                IEnumerable<SharePointItemBaseModel> childFolders = ProcessFolder(childFolder,context);
                folderModel.Items.AddRange(childFolders);
                listItems.Add(folderModel);
            }

            foreach (Microsoft.SharePoint.Client.File file in folder.Files)
            {
                DocumentModel documentModel = new DocumentModel();
                documentModel.Name = file.Title;
                documentModel.modifiedBy = file.ModifiedBy.ToString();
                listItems.Add(documentModel);
            }

            return listItems;
        }

        public ActionResult About()
        {
            return View();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

我自己设法解决了这个问题。

在我的递归方法中,我刚使用了

context.Load(folder.Folders);

context.Load(folder.Files);

这个初始化的集合允许我在我的foreach循环中使用它