I have AJAX call that works and return me JSON
Here is AJAX call
<script>
$('#display').click(function () {
var vacancyId = $("#vacancy").val();
var model = {
vacancyId: vacancyId
};
$.ajax({
url: '@Url.Action("QuestionBlocks", "Questions")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
$(".list").append('<div>' + data.Question1 + '</div>');
}
});
});
Here is server side
[HttpPost]
public ActionResult QuestionBlocks(int vacancyId)
{
var items = db.QuestionBlocks
.Where(x => x.Interview.VacancyId == vacancyId)
.Select(x => new
{
ID = x.Block_ID.ToString(),
Question1 = x.Question1,
Question2 = x.Question2,
Question3 = x.Question3,
Question4 = x.Question4,
Question5 = x.Question5,
Question6 = x.Question6,
Question7 = x.Question7,
Question8 = x.Question8,
Question9 = x.Question9,
Question10 = x.Question10,
})
.ToList();
return Json(items, JsonRequestBehavior.AllowGet);
}
It returns data like this
{ID: "1087", Question1: "Расскажите о себе", Question2: "Tell about you",…}
My problem in this - $(".list").append('<div>' + data.Question1 + '</div>'); works well, but it display undefined
Why so?
It sounds like you need to parse data to JSON. Try using it like this:
$(".list").append('<div>' + JSON.parse(data).Question1 + '</div>');
It seems like there is an array inside data, so try success code like this:
$.ajax({
url: '@Url.Action("QuestionBlocks", "Questions")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
var question1 = data[0];
$(".list").append('<div>' + question1.Question1 + '</div>');
}
});
I think it doesn't return {ID: "1087", Question1: "Расскажите о себе", Question2: "Tell about you",…}. Are you sure that? items will be array (ToList()).
[{ID: "1087", Question1: "Расскажите о себе", Question2: "Tell about you",…}]
So get first:
var question1 = data[0]
$(".list").append('<div>' + question1.Question1 + '</div>');