0

I have created an API that returns in json a list of type EventJOINEventDate. I am now trying to write a web form that calls the API and shows the Events from the json file in a table. The web form has 2 inputs: input_date and input_num. I wrote this far but am now stuck and don't know how to proceed. How do I use what I wrote to create an html table?

    string StartDate = input_date.ToString();
    string Num = input_num.ToString();
    string url = String.Format("Http://..."); //I have my url here
    WebRequest requestObj = WebRequest.Create(url);
    requestObj.Method = "GET";
    HttpWebResponse responseObj = null;
    responseObj = (HttpWebResponse)requestObj.GetResponse();
    string strresult = null;
    using (Stream stream = responseObj.GetResponseStream())
    {
        StreamReader sr = new StreamReader(stream);
        strresult = sr.ReadToEnd();
        sr.Close();
    }
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    List<EventJOINEventDate> EventList = (List <EventJOINEventDate>)serializer.Deserialize(strresult, typeof(List<EventJOINEventDate>));
    foreach(EventJOINEventDate obj in EventList)
    {
        long EventID = obj.EventID;
        DateTime StartDateTime = obj.StartDateTime;
        string EventName = obj.EventName;
        string EventDesc = obj.EventDesc;
        string Address1 = obj.Address1;
        string Address2 = obj.Address2;
        string City = obj.City;
        string State = obj.State;
        string Zip = obj.Zip;
        string EventURL = obj.EventURL;
        string RegistrationURL = obj.RegistrationURL;
        string InvitationURL = obj.InvitationURL;
    }
4
  • 1
    There are a lot of options. Do you have the HTML table (Repeater, DataGrid, etc..) already set up to to bind? Or are you wanting to create a new dynamic table via code-behind and render it out? Commented Aug 13, 2019 at 16:53
  • @JohnPete22 I haven't set anything up yet, and what I want is exactly what you said, to create a new dynamic table via code-behind and render it out. Commented Aug 13, 2019 at 16:56
  • Sounds like a lot of overhead to render server-side instead of just using a client side framework to consume the API and do the rendering. After all that's usually the point of having an API returning JSON. Commented Aug 13, 2019 at 17:03
  • @Filburt what would be the best way then to display in a table in html the json file that was retrieved from the API? Commented Aug 13, 2019 at 17:09

3 Answers 3

1

Okay, here is a quick solution for you. As another posted, client-side might be more efficient. But if you want to go server-side, you can take this approach and tailor it, add some styling to the Table/Rows/Cells.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="_testPWforSO.aspx.cs" Inherits="_testPWforSO" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:PlaceHolder ID="phTest" runat="server" />
        </div>
    </form>
</body>
</html>
using System;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

public class EventList
{
    public int Id { get; set; }
    public string EventName { get; set; }
    // more variables
}

public partial class _testPWforSO :  System.Web.UI.Page
{

    public void Page_Load(Object sender, EventArgs e)
    {
        EventList test = new EventList() { Id = 12, EventName = "test123" };
        EventList test1 = new EventList() { Id = 34, EventName = "test456" };
        List<EventList> events = new List<EventList>() { test, test1 };
        TestFunction(events);
    }

    public void TestFunction(List<EventList> events)
    {
        HtmlTable table = new HtmlTable();

        // add table headers if you want

        foreach (EventList item in events)
        {
            table.Rows.Add(AddRow(item));
        }

        phTest.Controls.Add(table);
    }

    public HtmlTableRow AddRow(EventList item)
    {
        HtmlTableRow result = new HtmlTableRow();

        result.Cells.Add(new HtmlTableCell() { InnerText = item.EventName });
        result.Cells.Add(new HtmlTableCell() { InnerText = item.Id.ToString() });

        return result;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Disclaimer: This answer tries to propose a different approach than the server-side / code-behind solution. It is meant as an alternative to illustrate ways to consume an API.

Using jquery, all you need is a static html page and few lines of js.

Since you didn't show the exact structure of your JSON, you will have to adjust according to your JSON properties.

<html>
<head/>
<body>

    <div>
        <table id="events" />
    </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
    var uri = 'your/url/here';

    $(document).ready(function () {
      // Send an AJAX request
      $.getJSON(uri)
          .done(function (data) {
            // On success, 'data' contains your json result.

          // Look for your column names
          var cols = Object.keys(data[0]);

          // create the table header
          var header = $('<thead />').appendTo('#events');

          for (var i = 0; i < cols.length; i++) {
              $('<th />', { text: cols[i] }).appendTo(header);
          }

          // create the table body
          var tBody = $('<tbody />').appendTo('#events');

          // create rows and cells
          for (var i = 0; i < data.length; i++) { // each row

              var row = $('<tr />').appendTo(tBody);

              for (var j = 0; j < cols.length; j++) { // each column

                  var obj = data[i];

                  $('<td />', {
                      text: obj[cols[j]]
                  }).attr('data-label', cols[j]).appendTo(row);
              }
          }
          });
    });
    </script>
</body>
</html>

Of course this is just raw table output. For adding more style you surely will want to use an existing jquery table plugin or a framework like Angular or Knockout.

Comments

0

You can do this with javascript. Make an ajax call to this method. In the response, you will get a Json. 1.) Convert it to an object in Javascript : - https://www.w3schools.com/js/js_json_parse.asp

Let us suppose that you got an array of objects 2.) Run a foreach loop [Loop 1] through array. Create a data row in this loop. : - https://www.w3schools.com/jsref/met_table_insertrow.asp

3.) Run a foreach loop [Loop 2] for each object in the array (Nested foreach inside [Loop 1] ). Create a table column and add the value of that column through javascript : - https://www.w3schools.com/jsref/met_tablerow_insertcell.asp

This should do it. Let me know if this solves it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.