Arash Arash - 4 months ago 13x
AngularJS Question

sending array json object using FormData() to mvc controller

i am trying to upload file to mvc controller using angular , everything works fine ,i get the file , even i have DTO as input parameter in my controller , it works fine , all members are binded by mvc except a member that is type of List .

here is my DTO

public class UpdateMeetingInput
public Guid Id { get; set; }
public string Subject { get; set; }
public DateTime Date { get; set; }
public DateTime EndTime { get; set; }
public string Description { get; set; }
public string Agenda { get; set; }
public bool IsCancelled { get; set; }
public List<AttendeeDto> Attendees {get;set;}
public string Location { get; set; }

and here is my javascript file

var fd = new FormData();
for (var key in meeting) {
// i will add attendees later
if (key != "attendees") {
fd.append(key, meeting[key])

fd.append('attendees', JSON.stringify(meeting.attendees));

$"/meeting/update", fd, {
headers: { 'Content-Type': undefined }

and here is my controller

public class MeetingController : TransitControllerBase
private readonly IMeetingManager _meetingManager;
private readonly IRepository<Meeting, Guid> _meetingRepository;
private readonly IRepository<Decision> _decisionRepository;
private readonly UserManager _userManager;

public MeetingController (IMeetingManager meetingManager, IRepository<Meeting, Guid> meetingRepository, IRepository<Decision> decisionRepository, UserManager userManager)
_meetingManager = meetingManager;
_meetingRepository = meetingRepository;
_decisionRepository = decisionRepository;
_userManager = userManager;
public async Task Update (UpdateMeetingInput input)

i watch attendees value using rerquest.form.getvalue("attendees") and i get the following string that is correct , but i dont know why mvc cant bind it do dto


am i doing something wrong in posting data ?


That's because you are using form data, which not json, but JSON.stringify formats your list as json, which is not what the model binder expects.

To resolve this, you can make the attendees a string in the model, and then de-serialize it explicitly in the controller from JSON.

Alternatively, instead you could try to use special syntax, attendees[] as field name (note the square brackets), instead of JSON.stringify. Like this:

for (var i = 0; i < attendees.length; i++) {
    fd.append('attendees['+i+'][userId]', attendees[i].userId);
    fd.append('attendees['+i+'][name]', attendees[i].name);