question

TimothyShels-8071 avatar image
0 Votes"
TimothyShels-8071 asked YijingSun-MSFT commented

How to populate GridView from an API call?

I am a beginner learning ASP.NET and I am working on a project where I need to create a Web API to get data from an SQL Server and then call that API from a Web Form to populate a gridview table.

I've currently gotten the Web API to properly get the SQL table and 'send' it to http://localhost:58749/api/Movie

Here is the code for my Web API Model and Controller classes:

namespace MovieAPI.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class tblMovie
    {
        public int MovieID { get; set; }
        public string MovieTitle { get; set; }
        public string MovieRating { get; set; }
        public int ReleaseYear { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MovieAPI.Models;
using System.Data;
using System.Data.SqlClient;

namespace MovieAPI.Controllers
{
    public class MovieController : ApiController
    {

        public IHttpActionResult getMovieDetails()
        {
            MoviesDBEntities entities = new MoviesDBEntities();
            var results = entities.tblMovies.ToList();
            return Ok(results);
        }

    }
}


When I press the play button in visual studio and then navigate to the appropriate URL, the output is something like this:
```
<ArrayOftblMovie xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MovieAPI.Models">;
<tblMovie>
<MovieID>1</MovieID>
<MovieRating>R </MovieRating>
<MovieTitle>From Dusk Til Dawn</MovieTitle>
<ReleaseYear>1996</ReleaseYear>
</tblMovie>
<tblMovie>
<MovieID>2</MovieID>
<MovieRating>R </MovieRating>
<MovieTitle>Neighbors</MovieTitle>
<ReleaseYear>2014</ReleaseYear>
</tblMovie>
<tblMovie>
<MovieID>4</MovieID>
<MovieRating>PG-13</MovieRating>
<MovieTitle>Avengers: Infinity War</MovieTitle>
<ReleaseYear>2018</ReleaseYear>
</tblMovie>
```

The problem I am running into is how to actually call the web API using HttpClient. I'm using HttpClient because I believe it is what is called for in the project. My Web Form backend looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Threading.Tasks;
using System.Net.Http;

namespace MovieWebForm
{
    public partial class Movie : System.Web.UI.Page
    {

        private void GetData()
        {
            DataTable table = new DataTable();
            // call Web API 

            //web api.Fill(table);

            GridView1.DataSource = table;
            GridView1.DataBind();
        }

        static readonly HttpClient client = new HttpClient();
        static async Task Main()
        {
            // Call asynchronous network methods in a try/catch block to handle exceptions.
            try
            {
                HttpResponseMessage response = await client.GetAsync("http://localhost:58749/api/Movie");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);



            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }


        protected async Task Page_LoadAsync(object sender, EventArgs e)
        {
            await Main();
        }
    }
}


The HttpClient code I have there is from the documentation example. I've been unable to get any response however, although it's possible I'm checking the wrong place. Furthermore, I'm not sure how to properly call the Web API in a way that would populate the gridview with the table data. I think the gridview outline I have would work if I knew how to properly call the Web API.

Any tips or suggestions?

dotnet-aspnet-webformsdotnet-aspnet-webapi
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @TimothyShels-8071 ,
I think you need to check if the IsSuccessStatusCode property is true. HttpClient does not throw any error when HTTP response contains an error code, but it sets the IsSuccessStatusCode property to false. If we want to treat HTTP error codes as exceptions, we can use HttpResponseMessage.EnsureSuccessStatusCode method. Do you have any exceptions? If the response contains success code as response, it means the response body contains the data in the form of JSON. ReadAsAsync method is used to deserialize the JSON object.

 if (response.IsSuccessStatusCode)

Best regards,
Yijing Sun

0 Votes 0 ·

0 Answers