简体   繁体   中英

Add ListItem to List Folder using Rest-Api

I have a problem with adding a ListItem in a specified Folder while using SharePoint 2013 REST api.

With the Client Object Model it would look like this:

    var creationInfo = new SP.ListItemCreationInformation();
    creationInfo.FolderUrl = "/Lists/MyList/MyFolder";
    var item = list.addItem(creationInfo );



    item.update();

    ctx.executeQueryAsync(
            Function.createDelegate(this, onSuccess),
            Function.createDelegate(this, onFail));

But when i'm trying to set the FolderUrl via the Rest Service

{ '__metadata' : { 'type': 'SP.Data.MyListListItem' }, 'Title': 'NewItemInFolder', 'FolderUrl': '/sites/example/Lists/MyList/MyFolder' }

I got an 400 Bad Request

I have also tried to first add a ListItem to the List and then update the FolderUrl but this also didn't work.

How can I add ListItem's to a List Folder in SharePoint using the Rest-Api ?

Edit:

 { '__metadata' : { 
            'type': 'SP.Data.MyListListItem',
            'type': 'SP.Data.ListItemCreationInformation'
    }, 
    'Title': 'NewItemInFolder',
    'FolderUrl': '/sites/example/Lists/MyList/MyFolder'
    }

I have now tried to use both ListItemEntityTypeFullName the Entity from my List and the ListItemCreationInformation but I also only get a 400 Bad Request.

And when i'm looking into the request with Fiddler I see that SharePoint is ignoring now my List Entity Type SP.Data.MyListItem

You should not use the REST api but instead use the listdata.svc

url: /_vti_bin/listdata.svc/[Name of List]
Header:Content-Type: application/json;odata=verbose
Body: {Title: "Title", Path: "/ServerRelativeUrl"}

I had the same problem but with REST api it won't work with the old svc it will.

You could consider the following solution, it consists of 3 steps listed below:

  • create a ListItem resource
  • get associated File resource and finally move it into folder

Example

function executeJson(options) 
{
    var headers = options.headers || {};
    var method = options.method || "GET";
    headers["Accept"] = "application/json;odata=verbose";
    if(options.method == "POST") {
        headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
    }   

    var ajaxOptions = 
    {       
       url: options.url,   
       type: method,  
       contentType: "application/json;odata=verbose",
       headers: headers
    };
    if("payload" in options) {
      ajaxOptions.data = JSON.stringify(options.payload);
    }  

    return $.ajax(ajaxOptions);
}



function createListItem(webUrl,listTitle,properties,folderUrl){
    var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
    return executeJson({
        "url" :url,
        "method": 'POST',
        "payload": properties})
        .then(function(result){
             var url = result.d.__metadata.uri + "?$select=FileDirRef,FileRef";
             return executeJson({url : url});
        })
        .then(function(result){
             var fileUrl = result.d.FileRef;
             var fileDirRef = result.d.FileDirRef;
             var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
             var url = webUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
             console.log(url);
             return executeJson({
                  "url" :url,
                  "method": 'POST',
                  });
        });
}

Usage

var webUrl = _spPageContextInfo.webAbsoluteUrl;
var listTitle = "Requests";  //list title
var targetFolderUrl = "/Lists/Requests/Archive";  //folder server relative url
var itemProperties = {
    '__metadata': { "type": "SP.Data.RequestsListItem" },
    "Title": 'Request 123'
};


createListItem(webUrl,listTitle,itemProperties,targetFolderUrl)
.done(function(item)
{
    console.log('List item has been created');
})
.fail(function(error){
    console.log(JSON.stringify(error));
});

Gist

Microsoft.SharePoint.Client.ClientContext clientContext = new Microsoft.SharePoint.Client.ClientContext("URL");

Microsoft.SharePoint.Client.List list = clientContext.Web.Lists.GetByTitle("FolderName");

var folder = list.RootFolder;

clientContext.Load(folder);

clientContext.Credentials = new NetworkCredential(username, password, domain);
clientContext.ExecuteQuery();

folder = folder.Folders.Add("ItemName");

clientContext.Credentials = new NetworkCredential(username, password, domain);
clientContext.ExecuteQuery();
creationInfo.set_folderUrl("http://siteURL/Lists/Docs/Folder1");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM