skip to Main Content

I have a ForumController where I have a function ChangeOrder with a ChangeOrderDto. Here is the code:

[HttpPost("change-order")]
public async Task<ActionResult> ChangeOrder([FromBody] ChangeOrderDto[] forums)
{
    foreach (var dto in forums)
    {
        var forum = await context.Forums.FindAsync(dto.Id);

        if (forum is not null)
        {
            forum.Order = dto.Order;
            forum.ParentId = dto.ParentId;
        }
    }

    await context.SaveChangesAsync();

    return Ok();
}
public class ChangeOrderDto
{
    public int Id { get; set; }
    public int Order { get; set; }
    public int ParentId { get; set; }
}

However when I post to /api/forum/change-order with json

{
  "forums": [
    {id: 3, order: 1, parent_id: 1},
    {id: 4, order: 2, parent_id: 1}
  ]
}

I get this error in response:
Validation failed, forums field is required.

I tried adding [FromBody("forums")] but it did not work.

2

Answers


  1. If I understand your requirement correctly, your JSON should look like this:

    [
        {"id": 3, "order": 1, "parent_id": 1},
        {"id": 4, "order": 2, "parent_id": 1}
    ]
    

    You may need to change "parent_id" to "parentId" as well since you don’t specify any custom property name for the JSON parser.

    It then would look like this (also formatted for legibility):

    [
        {
            "id": 3,
            "order": 1,
            "parentId": 1
        },
        {
            "id": 4,
            "order": 2,
            "parentId": 1
        }
    ]
    

    If you want to validate your JSON, you can also use a service like this one: https://jsonformatter.curiousconcept.com/

    Login or Signup to reply.
  2. Extrapolating on the answers from below your post (Jon Skeet and ewerspej), lets build this payload:

    First, You want to send an array of data:

    [
    
    ]
    

    This array have in your case 2 objects:

    [
      {
    
      },
      {
    
      }
    ]
    

    Objects you transferring have some properties with values:

    [
      {
        "id": 3,
        "order": 1,
        "parentId": 1
      },
      {
        "id": 4,
        "order": 2,
        "parentId": 1
      }
    ]
    

    Take a look especially at the name of parrentId property – I think this should be named like this in the payload instead of parent_id that You used in your payload.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search