2013-04-30 26 views
0

我有一個動作返回JsonResult類型,這是代碼:如何使用JQuery Ajax從ASP.NET MVC 2中的Action中獲取值?

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); 
    } 

我想使用jQuery的返回值,類似下面的C#(但使用jQuery,專賣店的結果,並把它變成#DIV1) :

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

我發現了一個解決方案,但它花費了單個對象:

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); 
     } 
    }); 
} 

我該怎麼辦?感謝觀看!

+0

** [請點擊這裏](http://stackoverflow.com/ a/16245682/2007801)**或** [here](http://stackoverflow.com/a/15794247/2007801)**或** [here](http://stackoverflow.com/a/1575 8449/2007801)** – 2013-05-01 07:25:14

回答

2

試試這個 -

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/

+0

謝謝。我會在嘗試後回覆。 – 2013-04-30 18:02:30

0

使用jQuery.each ..

試試這個

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); 
    } 
    }); 
} 
+0

謝謝。我會在嘗試後回覆。 – 2013-04-30 17:59:15

相關問題