Search code examples
c#asp.net-mvcswagger-ui

ASP.NET take in multiple swagger inputs using a foreach loop


I want to have my HTTPPost take in multiple inputs, the single input works just fine but when I want to put in multiple values like in the 2nd picture, it gave me a JSON error and said 'typeCreate field is required' single input multiple inputs

I tried adding a foreach loop in, but I don't know the correct implementation of it. For the code that runs normally, just remove the foreach loop. My TypeDto only has {get; set;} for Id and Type, same with TestModelType

        [HttpPost]
        [ProducesResponseType(204)]
        [ProducesResponseType(400)]
        public IActionResult CreateType([FromBody] TypeDto typeCreate)
        {
            if(typeCreate == null)
            {
                return BadRequest(ModelState);
            }
            foreach (typeCreate in _typeRepos.GetTypes) {
                    var type = _typeRepos.GetTypes()
                        .Where(t => t.Types.Trim().ToUpper() == typeCreate.Types.TrimEnd().ToUpper())
                        .FirstOrDefault();

                    if (type != null)
                    {
                        ModelState.AddModelError("Model Type", "Type already exists");
                        return StatusCode(422, ModelState);
                    }
                    if (!ModelState.IsValid)
                    {
                        return BadRequest(ModelState);
                    }
                    var typeMap = _mapper.Map<TestModelType>(typeCreate);
                    if (!_typeRepos.CreateType(typeMap))
                    {
                        ModelState.AddModelError("Error", "Can't save");
                        return StatusCode(500, ModelState);
                    }
                }
            return Ok("Succesfully created");
        }

Solution

  • Accept IEnumerable<TypeDto> instead.

            public IActionResult CreateType([FromBody] IEnumerable<TypeDto> typeCreate)
    

    The json request becomes like this:

    {
      [
         { "types": "string111" },
         { "types": "string222" }
      ]
    }
    

    Or, you can make Types in TypeDto become IEnumerable<string> instead, if it only has Types. You then iterate typeDto.Types instead.