Answer the question
In order to leave comments, you need to log in
How to display data on the client received from the server via JSON?
From the server we get: [{"Name":"Andrew","Surname":"Romanuk","Group":"1CS-16B"}]
In the view ( .html ):
<script type="text/javascript">
$(document).ready(function () {
$("#ourBtn").click(function () {
var name = $("#Name").val();
$.ajax({
type: 'GET',
dataType: 'json',
contentType:'application/JSON',
data: { Name: name},
url: '@Url.Action("SearchResult", "Home")',
success: function (data) {
alert(data); // [{"Name":"Andrew","Surname":"Romanuk","Group":"1CS-16B"}]
var student = jQuery.parseJSON(data);
alert(student.Name); //undefined
alert(student.Surname);//undefined
//(Названия свойств совпадает с полями в модели )
}
});
});
});
</script>
<form>
<input type="text" id="Name" name="Name" />
<input type="button" id="ourBtn" name="ourBtn" value="Отправить" />
</form>
[HttpGet]
public ActionResult SearchResult(string Name)
{
var result = OurDb.Students.Where(p => p.Name == Name)
.Select(p => new { Name = p.Name, Surname=p.Surname, Group = p.Group.NameOfGroup }).ToList();
var jsonUser = JsonConvert.SerializeObject(result);
return Json(jsonUser, JsonRequestBehavior.AllowGet);
}
Answer the question
In order to leave comments, you need to log in
Well, it's an array.
alert(student[0].Name); //Andrew
alert(student[0].Surname);//Romanuk
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question