Вопрос

I have a action return JsonResult type, this is code:

public JsonResult GetStudent()
    {
        var student1 = new Student
        {
            ID = 123456,
            Name = "John Smith",
            Grades = new int[] { 77, 86, 99, 100 }
        };

        var student2 = new Student
        {
            ID = 123456,
            Name = "John Smith",
            Grades = new int[] { 77, 86, 99, 100 }
        };

        List<Student> students = new List<Student>();
        students.Add(student1);
        students.Add(student2);

        return Json(students, JsonRequestBehavior.AllowGet);
    }

I want to use return value with Jquery, something like below in c# (but with Jquery, stores results, and put it into #div1):

foreach (var item in students)
{
    // scan and store
}

I found a solution but it spends for single object:

function GetStudent() {
    $.ajax({
        url: "/Ajax/GetStudent",
        success: function (student) {
            var stdnt = "ID: " + student.ID + "<br/>"
                + "Name: " + student.Name + "<br/>"
                + "Grades: " + student.Grades;
            // 
            $("#div1").html(stdnt);
        }
    });
}

What should I do? Thanks for watching!

Это было полезно?

Решение

Try this -

success: function (student) {
            $("#div1").html("");
            $.each(student,function(index,value){
                 stdnt = "ID: " + value.ID + "<br/>"
                 + "Name: " + value.Name + "<br/>"
                 + "Grades: " + value.Grades;
                 $("#div1").append(stdnt);
            });

        }

http://api.jquery.com/each/

Другие советы

use jQuery.each ..

try this

 function GetStudent() {
  $.ajax({
    url: "/Ajax/GetStudent",
    success: function (student) {
        var stdnt=""; 
        $.each(student,function(i,v){
          var stdnt += "ID: " + student.ID + "<br/>"
            + "Name: " + student.Name + "<br/>"
            + "Grades: " + student.Grades+ "<br/>";
        // 
          });
        $("#div1").html(stdnt);
    }
  });
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top