站点上不存在Sharepoint列表,但在调试时它存在于我的代码中

时间:2014-05-26 15:29:30

标签: sharepoint sharepoint-2013 csom

我最终会创建一个sharepoint日历。我想在这里创建一个事件列表,但我在这里会遇到这个奇怪的错误。

我创建了一个事件列表,然后检查[看看]它是否已创建。如果是,不是我想创建它,但我的testLabel说它已经存在。

当我尝试删除列表时,在myButton_Click上,它给了我这个错误:

  

Microsoft.SharePoint.Client.ServerException:List' CompanyCalendar'   在包含网址' http://server1'。

的网站上不存在

代码

using Microsoft.SharePoint.Client;

namespace CalendarWeb.Pages
{
public partial class Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

        Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);

        using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
        {
            Web web = clientContext.Web;
            ListCreationInformation listCreator = new ListCreationInformation();
            listCreator.Title = "CompanyCalendar";
            listCreator.Description = "Workcalendar";

            listCreator.TemplateType = (int)ListTemplateType.Events;
            var ifListExcists = web.Lists.GetByTitle(listCreator.Title);
            if (ifListExcists == null)
            {
                web.Lists.Add(listCreator);
                clientContext.ExecuteQuery();
                testLabel.Text = "The " + listCreator.Title + " list was created";
            }
            else
            {
                testLabel.Text = "List already excist";
            }
        }
    }

    protected void myButton_Click(object sender, EventArgs e)
    {
        Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);
        using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
        {
            Web web = clientContext.Web;

            var deleteList = web.Lists.GetByTitle("CompanyCalendar");
            deleteList.DeleteObject();
            clientContext.ExecuteQuery();
            testLabel.Text = "list deleted";
        }

    }
}
}

当我查看我的server1站点时,列表不存在,但在代码中它似乎就在那里,因为我的变量"ifListExcists"永远不会为空。

1 个答案:

答案 0 :(得分:2)

您的ifListExists变量永远不会为空,因为它未在服务器上执行。

使用以下方法检查列表是否存在:

private bool ValdiateList(ClientContext clientContext, string listName, out List existingList)    
{

    Web web = clientContext.Web;

    existingList =null;

    ListCollection lists = web.Lists;

    var existingLists 
                  = clientContext.LoadQuery(lists.Where(list => list.Title == listName));

    clientContext.ExecuteQuery();

    existingList = existingLists.FirstOrDefault();

    return (existingList != null);

}