Reputation: 219
I have this code on back-end controller
[HttpGet]
public ActionResult EmailsList()
{
var itemsEmail = db.InvitationMails
.Select(x=> new
{
Email = x.To.ToString(),
Name = x.Name.ToString(),
})
.ToList();
return Json(itemsEmail, JsonRequestBehavior.AllowGet);
}
This on AJAX call code
<script>
$('#save_quest').click(function () {
email_update();
});
function email_update() {
$.ajax({
url: '@Url.Action("EmailsList", "Questions")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (result) {
var email = result;
// console.log(result[0].Name);
for (var i = 0; i <= email.length - 1; i++){
var emailHTML = '<div style="margin-left: 25px; margin-top: 10px;>' + '<b style="margin-left: 10px;">' + result.Email + '<b>' + '<b style="margin-left: 20px;">' + result.Name + '</b>' + '</div>'
$(".email_list").append(emailHTML);
}
}
});
}
Code works well,but I have undefined
on View.
How I need to edit my code to display it correctly?
Upvotes: 1
Views: 168
Reputation: 1562
I'm writing this to help someone if he/she get the same issue,
Because of it's an array of objects, so you need to add [i] with your result inside your for loop.
for (var i = 0; i <= email.length - 1; i++)
{
var emailHTML = '<div style="margin-left: 25px; margin-top: 10px;>' + '<b style="margin-left: 10px;">' + result[i].Email + '<b>' + '<b style="margin-left: 20px;">' + result[i].Name + '</b>' + '</div>'
$(".email_list").append(emailHTML);
}
Cheers :)
Upvotes: 2