Search code examples
jqueryasp.net-mvc-2asp.net-ajaxjsonresult

How to use Jquery Ajax to get values from Action in ASP.NET MVC 2?


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!


Solution

  • 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/