How to add an item in a sharepoint list, for a choice.

Jean-Sébastien Dufour 0 Reputation points
2024-11-28T19:16:38.8566667+00:00

Hi,

I am trying using c# to create an item in a sharepoint list. I try directly in the graph explorer, and i can create a sharepoint list item directly in it if the field is basic ( text or number). But when it comes to a choice column i failed. I keep receiving a 400 error


{
    "fields": {
        "Title": "Test2",
        "ColumnLayout": "One column",
        "Tags": {
            "Tags@odata.type": "Collection(Edm.String)",
            "Tags":["Politiques","Directives"]
		},
        "MasterLayout": "Politique"
    }
}

In the graph explorer I tried the follow using post and i keep getting invalid request. I know if i remove the tags then it works.

I follow this: https://learn.microsoft.com/en-us/answers/questions/813838/create-listitem-with-choice-column

In order to add the @odata.type

In c# I try the following, but i can't get the query to work

var listItem = new
{
   fields = new Dictionary<string, object>
   {
        { "Title", currentRecord.Title },
        { "Departments", selectedDepartments.ToArray() }, // Array of strings
   }
};
string jsonString = JsonSerializer.Serialize(listItem, new JsonSerializerOptions { WriteIndented = true });
var response = await SharePointGraphService.PostSharePointListItemAsync(spSiteID, spDocumentListID, jsonString);

.....

public async Task<string> PostSharePointListItemAsync(string siteId, string listId, string listItem)
{
   try
   {
      var accessToken = await GetAccessTokenAsync();
      _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

      var url = $"https://graph.microsoft.com/v1.0/sites/{siteId}/lists/{listId}/items/3";
      var content = new StringContent(listItem, Encoding.UTF8, "application/json");
      var response = await _httpClient.PatchAsync(url, content);
      response.EnsureSuccessStatusCode();
      var responseContent = await response.Content.ReadAsStringAsync();
      return responseContent; // Parse as needed
   }
   catch (Exception ex)
   {
     Console.WriteLine(ex.Message);
     return string.Empty;
   }
}

Any solution or is this not possible?

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,441 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,084 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
3,095 questions
0 comments No comments
{count} votes

Accepted answer
  1. AllenXu-MSFT 21,436 Reputation points Microsoft Vendor
    2024-11-29T06:05:30.5+00:00

    Hi @Jean-Sébastien Dufour,

    We are glad to hear that this issue has been resolved. Thanks for sharing the solution here and your great contribution to our community. As we have a policy that the user cannot accept the answer by themselves as the answer, I would make a brief summary here and you can accept this answer to help us archive this issue so that others who stuck in similar issues could get answered quickly.

    [Issue symptoms]:
    Receiving a 400 error when creating list item which contains a choice field using graph API:

    
    {
        "fields": {
            "Title": "Test2",
            "ColumnLayout": "One column",
            "Tags": {
                "Tags@odata.type": "Collection(Edm.String)",
                "Tags":["Politiques","Directives"]
    		},
            "MasterLayout": "Politique"
        }
    }
    
    
    

    [Solution]:

    In the json I was wrapping the tags while not needed.

    {
        "fields": {
            "Title": "Test2",
            "ColumnLayout": "One column",
                "Tags@odata.type": "Collection(Edm.String)",
                "Tags":["Politiques","Directives"]
            "MasterLayout": "Politique"
        }
    }
    
    

    Have a good day!

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jean-Sébastien Dufour 0 Reputation points
    2024-11-29T02:59:09.7333333+00:00

    Found the issues

    In my json I was wrapping the tags while not needed.

    {
        "fields": {
            "Title": "Test2",
            "ColumnLayout": "One column",
                "Tags@odata.type": "Collection(Edm.String)",
                "Tags":["Politiques","Directives"]
            "MasterLayout": "Politique"
        }
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.