Home > database >  List of objects and image is not being passed (Registered) with FromForm POST Call
List of objects and image is not being passed (Registered) with FromForm POST Call

Time:08-18

i have a model class of the following..

public class RegisterDTO
{
    public string Name{ get; set; }
    public string Location { get; set; }
    public string PhoneNumber { get; set; }
    public IFormFile Image { get; set; }
    public List<string> Days { get; set; }

    //here is the list of costs
    public List<CostDTO> Costs { get; set; }

    public IFormFile Image1 { get; set; }
    public IFormFile Image2 { get; set; }
}

and here is the CostDTO class

public class CostDTO
{
    public string itemName { get; set; }
    public bool isPercent { get; set; }
    public float value { get; set; }
}

and here is the service for registering the values stated above..

    public async Task <string> Register(RegisterDTO model)
   {
       var entity = await _context.Tablename.FirstOrDefaultAsync();
       List<Cost> costs = new();
      //here is the loop that maps the DTO to an entity and stores it into the list

                foreach (var item in model.costs)
                {
                    var cost = _mapper.Map<Cost>(item);
                    costs.Add(cost);
                }
      //then save to the database
   }

And here is the controller that calls the service.

    [HttpPost("info")]
    public async Task<ActionResult> Register([FromForm] RegisterDTO model)
    {
        var result = await _serviceName.Register(model);
        return Ok(result);
    }

My question is, at the beginning of the for loop, model.costs is empty and its not allowing me to pass a list of objects onto the service call. how do i go about fixing this.

CodePudding user response:

you can fix it like this costs[0].itemName="item1",costs[1].itemName="item 2", but it's not good solution, it's better to separate your dto ,get images in a model use [fromform] and another model [frombody]

CodePudding user response:

As Hossein said, you should firstly make sure the request has sent the Costs list to the web api controller method.

The asp.net core model binding will auto map the formdata array with the list. So you should use it like below: enter image description here

Then the result:

enter image description here

  • Related