如何使用.asmx Web服务将项目添加到Sharepoint列表

时间:2012-07-06 05:38:15

标签: c# winforms list sharepoint-2010 asmx

我在项目中使用了asmx web服务。我想将项目添加到现有SharePoint列表。

   mylist.Url = Url.TrimEnd('/') + "/_vti_bin/lists.asmx";
            mylist.UseDefaultCredentials = true;
            XmlNode node = mylist.GetList(_listName);

我已将我的值存储在DataTable中。如何从C#Datatable直接将数据添加到SharePoint列表? 或者我应该将其转换为Xml并添加?

谢谢

2 个答案:

答案 0 :(得分:7)

请查看this page以了解UpdateListItems的一般用法,尽管它只有更新项目的示例。

然后查看this page,了解您需要发送的XML示例,以创建项,而不是更新现有项。

您需要遍历数据表,为要添加的每个项目构建XML结构,但您可以在一个请求中添加它们。

答案 1 :(得分:0)

以下示例演示了如何使用SharePoint Web Services,特别是Lists Class来创建列表项:

using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;

namespace SharePoint.Client
{
    public class ListsClient : IDisposable
    {
        public ListsClient(Uri webUri, ICredentials credentials)
        {
            _client = new Lists.Lists();
            _client.Credentials = credentials;
            _client.Url = webUri + "/_vti_bin/Lists.asmx";
        }

        public ListsClient(Uri webUri)
        {
            _client = new Lists.Lists();
            _client.Url = webUri + "/_vti_bin/Lists.asmx";
        }


        /// <summary>
        /// Create a List Item 
        /// </summary>
        /// <param name="listName">List Name</param>
        /// <param name="propertyValues">List Item properties</param>
        /// <returns></returns>
        public XmlNode CreateListItem(string listName,Dictionary<string,string> propertyValues)
        {
            var payload = new XmlDocument();
            var updates = payload.CreateElement("Batch");
            updates.SetAttribute("OnError", "Continue");
            var method = payload.CreateElement("Method");
            method.SetAttribute("ID", "1");
            method.SetAttribute("Cmd", "New");
            foreach (var propertyValue in propertyValues)
            {
                var field = payload.CreateElement("Field");
                field.SetAttribute("Name", propertyValue.Key);
                field.InnerText = propertyValue.Value;
                method.AppendChild(field);
            }
            updates.AppendChild(method);
            return _client.UpdateListItems(listName, updates);
        }



        public void Dispose()
        {
            _client.Dispose();
            GC.SuppressFinalize(this);
        }


        protected Lists.Lists _client;  //SharePoint Web Services Lists proxy

    }
}

<强>用法

如何创建任务项:

using (var client = new SPOListsClient(webUrl, userName, password))
{
    var taskProperties = new Dictionary<string, string>();
    taskProperties["Title"] = "Order approval";
    taskProperties["Priority"] = "(2) Normal";
    var result = client.CreateListItem(listTitle, taskProperties);    
}

参考