سؤال

I am using asp.net mvc4 with C#. I get the details from Getdeatils() method of student class. This method return an array. Getdetails method also have same fields like studentBO. In the controller I have a method like follows

   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 object have 3 fields

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.
هل كانت مفيدة؟

المحلول

You can serialise your item in the ViewBag and write it to the view, so that the Javascript code will be able to read it:

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

نصائح أخرى

Use WebAPI to create a service that returns your objects. Then you can use an ajax-call in your Javascript code to fetch the objects.

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
        });
      });
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top