Update multiple choice field in sharepoint using rest api

前端 未结 1 1684
不思量自难忘°
不思量自难忘° 2021-01-15 05:07

I am trying to update the multiple choice field in sharepoint online using rest api. I am getting 401 bad request error.

HttpWebRequest request = (HttpWebRe         


        
相关标签:
1条回答
  • 2021-01-15 05:58

    Most likely the payload is invalid in your example:

    string stringData = 
    @"{'__metadata': { 'type':'SP.ListItem' }, 
    'TestColumn': { '__metadata': { 'type' : 'Collection(Edm.String)', results: ['Test1']}}}";
    

    The point is the type SP.ListItem corresponds to Generic list, in your example it is a Documents library.

    So, a valid entity type name needs to be provided, you could utilize the following endpoint to determine metadata type:

    Endpoint:

    Url: /_api/lists/getbytitle('<list title>')?$select=ListItemEntityTypeFullName
    Method: GET
    

    Secondly, the Update operation requires the following properties to be specified with request:

    • Create an HTTP request using the POST verb.
    • Add an X-HTTP-Method header with a value of MERGE.
    • Add an If-Match header with a value of the entity’s original ETag.

    You could refer this post for a more details.

    And last but no least, Content-Type and Accept request headers needs to be specified (follow this article for a more details), for example:

    request.Accept = "application/json;odata=verbose";
    request.ContentType = "application/json;odata=verbose";
    

    The following example summarizes it and demonstrates how to update multi-choice field value:

    var requestUrl = $"{webUrl}/_api/web/getfilebyserverrelativeurl('{fileUrl}')/ListItemAllFields";
    var request = (HttpWebRequest)WebRequest.Create(requestUrl);
    request.Credentials = GetCredentials(userName, password);
    request.Accept = "application/json;odata=verbose";
    request.ContentType = "application/json;odata=verbose";
    request.Method = "POST";
    request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
    request.Headers.Add("X-RequestDigest", formDigestVal);
    request.Headers.Add("X-HTTP-Method", "MERGE");
    request.Headers.Add("If-Match", "*");
    
    
    var payload = @"{
                            '__metadata': { 'type':'SP.Data.Shared_x0020_DocumentsItem' },
                            '<ColumnName>': { '__metadata': { 'type' : 'Collection(Edm.String)'}, results: ['Val1']}
            }";
    
    request.ContentLength = payload.Length;
    var writer = new StreamWriter(request.GetRequestStream());
    writer.Write(payload);
    writer.Close();
    
    var response = (HttpWebResponse)request.GetResponse();
    
    0 讨论(0)
提交回复
热议问题