Arash Arash - 2 years ago 190
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

"[{\"userId\":0,\"name\":null,\"role\":\"4\",\"email\":\"[email protected]\",\"isGuest\":false,\"$$hashKey\":\"object:311\"}]"

am i doing something wrong in posting data ?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download