Can anyone help me with the following. I'm trying to POST JSON data to a controller, but the controller never populates the variable with the data.
This is the controller and always displays null.
This is the controller.
public ActionResult SyncMail(List<MailSyncDTO> emailLst)
{
return null;
}
The view looks like this;
foreach (var item in Model)
<td><input name="emailLst.emailSource" id="emailSource" type="text" value="@item.emailSource" /></td>
<td><input name="emailLst.emailDestination" id="emailDestination" type="text" value="@item.emailDestination" /></td>
<td><input name="emailLst.SyncMail" id="SyncMail" type="checkbox" /></td>
<td><input name="emailLst.ID" id="ID" type="text" value="@item.ID" hidden /></td>
</tr>
}
function Update() {
var emailLst = [];
$('#tblEmails tr').each(function () {
var obj = new Object();
var emailSource = $(this).find("input").each(function () {
if (this.id == 'emailSource' && this.value != '') {
obj.emailSource = this.value;
}
else if (this.id == 'emailDestination' && this.value != '') {
obj.emailDestination = this.value;
}
else if (this.id == 'SyncMail' && this.value != '') {
obj.SyncMail = this.value;
}
else if (this.id == 'ID' && this.value != '') {
obj.ID = this.value;
}
})
emailLst.push(obj);
});
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/MailSyncDBs/SyncMail',
data: JSON.stringify({ emailLst: emailLst })
});
}
I can see in Fiddler that the data is being sent.
POST http://localhost:53545/MailSyncDBs/SyncMail HTTP/1.1
Content-Type: application/json; charset=utf-8
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
Referer: http://localhost:53545/MailSyncDBs/Index
Accept-Language: en-GB
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Length: 336
Host: localhost:53545
Connection: Keep-Alive
Pragma: no-cache
{"emailLst":[{},{"emailSource":"source@mail.co.uk","emailDestination":"destination@mail.co.uk","SyncMail":"on","ID":"1"},{"emailSource":"source1@mail.co.uk","emailDestination":"destination1@mail.co.uk","SyncMail":"on","ID":"2"},{"emailSource":"source2@mail.co.uk","emailDestination":"destination2@mail.co.uk","SyncMail":"on","ID":"3"}]}
This is the DTO that is referenced;
public class MailSyncDTO
{
public string ID { get; set; }
public string emailSource { get; set; }
public string emailDestination { get; set; }
public string SyncMail { get; set; }
}