Home > Back-end >  Sending list of objects to ASP.NET Core Web API controller
Sending list of objects to ASP.NET Core Web API controller

Time:12-23

It seems things have become more complex going from ASP.NET MVC to .NET Core because I can no longer easily send List of objects to controller using Ajax. Please point me to what I am doing wrong.

In my controller, I have this method:

[HttpPost("EditMultipleResults")]
[Consumes("application/x-www-form-urlencoded")]
public bool EditMultipleResults([FromForm] List<Result>, [FromForm] string comment)
{
    // do something...
    return true;
}

Result is defined here

public class Result
{
    [Key]
    public long taskcd { get; set; } 
    public long Runno { get; set; }
    public string Workorder {get; set;}       
}

In my JS Ajax I have:

var results = [
{taskcd: 123,
 Runno: 187776876,
 Workorder: 'VA1234567'
},
{taskcd: 642,
 Runno: 187776877,
 Workorder: 'VA1234569'
},
{taskcd: 766,
 Runno: 187776876,
 Workorder: 'VA1234564'
}
];


 var posteddata = {
            results: results,
            comment: 'test comment'
        };

// call the controller
$.ajax({
            type: 'POST',         
            data: posteddata,            
            traditional: true,
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',          
            url:  'api/ResultsEditor/EditMultipleResults',
            success: function () {
                deferred.resolve();
            },
            error: deferred.reject
        });
        return deferred.promise();

My problem is that results list and reason are null when in controller. Any tricks to passing list of objects to controller in .NET Core 5? Thank you!

Another question: is there a way to see the data that's being passed to controller in dev tools?

CodePudding user response:

Because you are creating form data as a json object manually, instead of posting an html form, you need to encode that data as x-www-form-urlencoded manually also.

This post has some great suggestions. Make sure to read not just the accepted answer.

CodePudding user response:

you can't use [FromForm] (as well as [FromBody]) multiple times, your action input parameter should be the same as it is in ajax, so you will have to create a class

   public class PostedData
    {
        public List<ResultItem> Results { get; set; }
        public string Comment { get; set; }
    };

and action

public bool EditMultipleResults(PostedData data)
{
    // do something...
    return true;
}

and you don't need to use [Consumes("application/x-www-form-urlencoded")] ,[FromForm] and contentType: 'application/x-www-form-urlencoded; charset=utf-8' since all of them are already by default.

  • Related