首页 > 解决方案 > 如何使用 sharepoint rest api 使用相同的方法更新和创建项目

问题描述

我有一个要求,如果列表项已经存在,我需要更新它,如果该项目不存在,我需要创建一个新的。当我从自定义表单获取数据以更新项目时,我需要从单一方法管理的一切。有没有办法在sharepoint online rest api中做到这一点?我正在使用以下方法来更新项目

public static UpdateSaveSectionC(formData: any,id:any): PromiseLike<string> {

    // Return a promise
    const siteURL= "https://abc.sharepoint.com/sites/process";
    return new Promise((resolve, reject) => {
        for (var i = 0; i < formData.Category.length; i++) {

        const restUrl = siteURL + `/_api/web/lists/getbytitle('List')/items(${id[i]})`;
        const headers = { 'accept': 'application/json;odata=verbose', 'content-Type': 'application/json;odata=verbose','X-HTTP-Method': 'MERGE','IF-MATCH': '*'};
        const listTitle = "List";
        const data = {
                        '__metadata': { 'type': 'SP.Data.' + listTitle + 'ListItem','results':[] },
                        Category: formData.Category[i],
                        Recommendationsuggestion: formData.Recommendationsuggestion[i],

                    }  

            Helper.executeJson(restUrl, "POST", headers, JSON.stringify($.extend(true,{}, data)))
            .then((response) => {
                // Resolve the request

                resolve("success");
            }).catch( (e) => {
                if(e.responseJSON.error.message.value.indexOf("The request ETag value") != -1)
                {
                    resolve("Please refresh the page, and resubmit your changes");
                }

    });

}

`

标签: restsharepointsharepoint-onlineoffice365apisharepoint-rest-api

解决方案


使用rest api过滤列表以根据唯一键确认项目不存在,

/_api/web/lists/getbytitle('list title')/items?$filter=UniqueField eq 'value'

根据退回的物品数量来了解结果。


推荐阅读