1

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.

Rohit Pandey
  • 119
  • 4
  • 15

3 Answers3

2

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>
Pragnesh Khalas
  • 2,908
  • 2
  • 13
  • 26
1

I don't know if this is what you are looking for, but while parsing a json-string with several objects, you could simply use for each. Inside the loop you could create your grid, so you are depeding on the number of objects.

$.each(jsonstring, function (i, object) {
/*create your grid and handle your object here*/
/*access attributes of your object with object.attributname*/
}

Is this what you are looking for?

Janna
  • 61
  • 8
1

Assuming you are trying to consume the API in JavaScript.

There are two ways way to consume the same

  1. $.getJSON()
  2. $.ajax() For Details check this out : Difference Between $.getJSON() and $.ajax() in jQuery

JavaScript is very open,flexible and Object oriented at heart. So the result which you'll get from the above will be JavaScript object and you can play with the same via loops to get your expected result.

function example() {

    var data = [{ "Roll": "1", "Name": "A" }, { "Roll": "2", "Name": "B" }, { "Roll": "3", "Name": "C" }];

    for (var index = 0; index < data.length; index++) {
        var item = data[index];
        // Play with your data item for eg
        console.log(item.Roll);
        console.log(item.Name);
    }

    // JSON being javascript object
    // you can attach properties at run time too
    data.Source = "AJAXCall Blah";

   // Later in JS same can be used in appropriate scope.
    console.log(data.Source);
};


    $.each(dataReturnedFromAJAXCall,function(item){
    // play with your data here

});

How do I iterate over a JSON structure?
http://www.w3schools.com/js/js_json.asp

Community
  • 1
  • 1