2014-05-09 57 views
0

我正在用C#使用asp.net mvc4。我從Getdeatils()學生班的方法中獲得詳細信息。這個方法返回一個數組。方法Getdetails也有相同的字段,如studentBO。在控制器我有一個方法,像如下何傳遞一個模型對象或一個Viewbag到Javascript?

public ActionResult Index() 
      { 
      List<studentBO> list = new List<studentBO>(); 
        Student.GetDetails[] dt = Student.Getdeatils(); 
       for (int i = 0; i < dt.Length; i++) 
       { 

          studentBO.name= dt[i].name; 
          studentBO.studentno= dt[i].studentno; 
          studentBO.address= dt[i].address; 
          list1.Add(studentBO); 
        }  
      ViewBag.Registrationlist = list1; 
      return View(list1); 
     } 

studentBO對象有3個領域

public class studentBO 
    {  
     public long studentno{ get; set; } 
     public string name{ get; set; } 
     public string address{ get; set; } 
} 

How can I get viewbag or model in my Jquery `$(document).ready(function() {}` function. I want to get every students name. So I have to use foreach loop as well. 

回答

1

您可以在ViewBag連載您的項目,並將其寫入到視圖,從而使Javascript代碼將能夠閱讀:

$(document).ready(function() { 
    var registrationList = @(Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.Registrationlist))); 
    for (var i = 0; i < registrationList.length; i++) { 
     var studentno = registrationList[i].studentno; 
     var name= registrationList[i].name; 
     var address= registrationList[i].address; 
     // write some more code to make use of the values 
    } 
}); 
+0

謝謝Stefano Dalpiaz。 var registrationList是一個對象,那麼如何獲取特定文件的值?我想獲得studentno和名字。 – Dino

+0

該變量應該呈現爲Javascript數組,因此可能會有多個學生在其中。我修改了我的答案以顯示如何獲取這些值。 –

+0

非常感謝Stefano Dalpiaz。它的作品:) – Dino

1

使用的WebAPI創建返回您的對象的一項服務。然後,您可以在您的Javascript代碼中使用ajax-call來獲取對象。

的WebAPI:

public class StudentsController : ApiController 
{ 
    IEnumerable<Student.GetDetails> GetDetails() 
    { 
     List<studentBO> list = new List<studentBO>(); 

     Student.GetDetails[] dt = Student.Getdeatils(); 

     for (int i = 0; i < dt.Length; i++) 
     { 

      studentBO.name= dt[i].name; 
      studentBO.studentno= dt[i].studentno; 
      studentBO.address= dt[i].address; 

      list1.Add(studentBO); 
     } 

     return list1; 
    } 
} 

的Javascript:

$(document).ready(function() { 
    // Send an AJAX request 
    $.getJSON("api/students") 
     .done(function (data) { 
     // On success, 'data' contains a list of students. 
     $.each(data, function (key, item) { 
      //Do something with the student object 
     }); 
     }); 
});