Search code examples
asp.net-mvc-5asp.net-ajaxgetjsonasp.net-web-api2

using $.GetJSON() function to retrieve an array of class objects


I have implemented a WEB API 2 controller which returns an array of a class objects. Now, I want to consume this API in my MVC 5 application. For that I have found out that getJSON method can be used. But the problem is I don't know how to get an array of class objects from getJSON method. Also depending on the number of objects returned i have to create equal number of grids on UI. Any pointer, link or sample code is welcome.


Solution

  • Below example will help you to consume web api and use that data in your page.

    Controller :-

    public class TestController : ApiController
        {
          public IEnumerable<temp> Get()
            {
              var context = new Test();
              return context.temps;
            }
        }
    

    Model & DbContext Class For Database:-

    [Table("temp")]
    public class temp
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column(TypeName = "numeric")]
        public decimal tempid { get; set; }
    
        [Required]
        [StringLength(50)]
        public string name { get; set; }
    
        [Required]
        [StringLength(50)]
        public string address { get; set; }
    }
    
    public class Test : DbContext
     {
        public Test()
            : base("name=Test")
        {
        }
        public virtual DbSet<temp> temps { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<temp>()
                .Property(e => e.tempid)
                .HasPrecision(18, 0);
        }
    }
    

    View Side :-

    <html>
      <head>
        <script src="~/Scripts/js/jquery-1.10.1.min.js"></script>
        <script>
           $(document).ready(function()
            {
                $.getJSON("http://localhost:51197/api/Test", function (data) {
                $.each(data, function (key, val) {
                    $("<table border='1'><tr><td>" + val.name + "</td><td>" + val.address
                           + "</td></tr></table>").appendTo("#tbPerson");
                });
             });
           });
        </script>
    </head>
    <body>
      <div id="tbPerson">
      </div>
    </body>
    </html>