0% found this document useful (0 votes)
13 views9 pages

Web api lec 18

The document provides a comprehensive guide on how to load JSON data from a Web API and display it in a grid using ASP.NET Core and ASP.NET Web Forms. It covers key concepts such as Web API, JSON, and LINQ, and outlines a step-by-step approach for fetching, processing, and displaying the data. Sample code snippets are included for both ASP.NET Core and ASP.NET Web Forms implementations.

Uploaded by

farwaakhtarrana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views9 pages

Web api lec 18

The document provides a comprehensive guide on how to load JSON data from a Web API and display it in a grid using ASP.NET Core and ASP.NET Web Forms. It covers key concepts such as Web API, JSON, and LINQ, and outlines a step-by-step approach for fetching, processing, and displaying the data. Sample code snippets are included for both ASP.NET Core and ASP.NET Web Forms implementations.

Uploaded by

farwaakhtarrana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Load json data from any Web API and use LINQ to JSON to read and

display on grid using MVC

Understanding the Key Concepts


1. Web API
A Web API is an application programming interface for the web that provides endpoints for clients to
interact with, often delivering JSON data. For this example, we'll use a public API:
https://jsonplaceholder.typicode.com/posts.

2. JSON
JSON (JavaScript Object Notation) is a lightweight data format used for data interchange. It's easy to
read and write for humans and easy to parse and generate for machines.

3. LINQ
Language Integrated Query (LINQ) in C# allows querying objects, databases, XML, or JSON. It provides a
way to filter, select, and transform data in a readable and maintainable way.

4. Three-Step Approach

• Fetch JSON Data from the Web API.


• Parse and Query JSON using LINQ.
• Bind Data to a GridView for display.

Implementation in ASP.NET Core


Step 1: Create a New ASP.NET Core Project

1. Open Visual Studio and select File > New > Project.
2. Choose the ASP.NET Core Web Application template.
3. Select Web Application (Model-View-Controller).
4. Name your project and click Create.

Step 2: Fetch JSON Data


Use HttpClient to fetch JSON data from the Web API.

Code: ApiService.cs
This service will handle HTTP requests to the Web API.

using System.Net.Http;
using System.Threading.Tasks;

namespace YourProject.Services
{
public class ApiService
{
private readonly HttpClient _httpClient;

public ApiService(HttpClient httpClient)


{
_httpClient = httpClient;
}

public async Task<string> GetJsonDataAsync(string url)


{
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
throw new HttpRequestException("Failed to fetch data from the API.");
}
}
}
Step 3: Process and Query JSON Data Using LINQ
Use System.Text.Json to parse and query JSON data.

Code: JsonProcessor.cs
This class parses JSON and queries it using LINQ.

using System.Collections.Generic;
using System.Linq;
using System.Text.Json;

namespace YourProject.Utilities
{
public static class JsonProcessor
{
public static List<dynamic> ProcessJson(string jsonData)
{
var jsonDocument = JsonDocument.Parse(jsonData);
var jsonArray = jsonDocument.RootElement.EnumerateArray();

return jsonArray
.Select(item => new
{
Id = item.GetProperty("id").GetInt32(),
Title = item.GetProperty("title").GetString(),
Body = item.GetProperty("body").GetString()
})
.Cast<dynamic>()
.ToList();
}
}
}

Step 4: Display Data in a Razor View


Controller
Create a controller to fetch and pass data to the view.

using Microsoft.AspNetCore.Mvc;
using YourProject.Services;
using YourProject.Utilities;

namespace YourProject.Controllers
{
public class DataController : Controller
{
private readonly ApiService _apiService;

public DataController(ApiService apiService)


{
_apiService = apiService;
}

public async Task<IActionResult> Index()


{
string apiUrl = "https://jsonplaceholder.typicode.com/posts";
string jsonData = await _apiService.GetJsonDataAsync(apiUrl);
var processedData = JsonProcessor.ProcessJson(jsonData);

return View(processedData);
}
}
}

Razor View
Create a Razor View Index.cshtml to display the data in a table.

html
@model List<dynamic>

<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Title</td>
<td>@item.Body</td>
</tr>
}
</tbody>
</table>

Implementation in ASP.NET Web Forms


Step 1: Fetch JSON Data Using HttpClient
Code: ApiHelper.cs
Use HttpClient to fetch JSON data.

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace YourProject.Helpers
{
public static class ApiHelper
{
public static async Task<string> FetchJsonDataAsync(string apiUrl)
{
using (HttpClient client = new HttpClient())
{
var response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
throw new Exception("Error fetching JSON data.");
}
}
}
}
Step 2: Parse JSON Data Using LINQ
Code: JsonProcessor.cs
Process JSON using Newtonsoft.Json.

using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace YourProject.Helpers
{
public static class JsonProcessor
{
public static List<dynamic> ProcessJson(string jsonData)
{
var jsonArray = JArray.Parse(jsonData);

return jsonArray
.Select(item => new
{
Id = (int)item["id"],
Title = (string)item["title"],
Body = (string)item["body"]
})
.Cast<dynamic>()
.ToList();
}
}
}

Step 3: Display Data in GridView


ASPX Markup
html

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" />


Code-Behind
Fetch, process, and bind JSON data to GridView.

using System;

using System.Threading.Tasks;

using YourProject.Helpers;

public partial class DisplayData : System.Web.UI.Page


{

protected async void Page_Load(object sender, EventArgs e)


{

if (!IsPostBack)
{

string apiUrl = "https://jsonplaceholder.typicode.com/posts";

string jsonData = await ApiHelper.FetchJsonDataAsync(apiUrl);

var processedData = JsonProcessor.ProcessJson(jsonData);


GridView1.DataSource = processedData;

GridView1.DataBind();

Sample JSON API


The API https://jsonplaceholder.typicode.com/posts provides:
json
[
{ "id": 1, "title": "Title 1", "body": "Body 1" },
{ "id": 2, "title": "Title 2", "body": "Body 2" }
]
Load json data from any Web API and use LINQ to JSON to read and
display on grid using ASP.NET Web Forms

1. Setup the ASP.NET Web Forms Project


1. Create a new ASP.NET Web Forms project in Visual Studio.
2. Add a new Web Form (e.g., DisplayData.aspx).

2. Fetch JSON Data Using HttpClient


You can use HttpClient to fetch the JSON data from the Web API.

Code: ApiHelper.cs
Add a helper class to fetch JSON data.

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace YourProject.Helpers
{
public static class ApiHelper
{
public static async Task<string> FetchJsonDataAsync(string apiUrl)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
throw new Exception("Error fetching JSON data.");
}
}
}
}
3. Parse and Process JSON Using LINQ
Use Newtonsoft.Json or System.Text.Json for parsing JSON. For simplicity, we'll use
Newtonsoft.Json.

Code: JsonProcessor.cs
Add a helper class to parse JSON and process it using LINQ.

using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace YourProject.Helpers
{
public static class JsonProcessor
{
public static List<dynamic> ProcessJson(string jsonData)
{
var jsonArray = JArray.Parse(jsonData);

return jsonArray
.Select(item => new
{
Id = (int)item["id"],
Title = (string)item["title"],
Body = (string)item["body"]
})
.Cast<dynamic>()
.ToList();
}
}
}
4. Create the User Interface (GridView)
In the DisplayData.aspx file, add a GridView control.

Markup: DisplayData.aspx
html
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="DisplayData.aspx.cs" Inherits="YourProject.DisplayData" %>

<!DOCTYPE html>
<html>
<head runat="server">
<title>Display Data</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" />
</form>
</body>
</html>

5. Fetch and Bind Data in Code-Behind


In the DisplayData.aspx.cs file, fetch the JSON data, process it using LINQ, and bind it to the
GridView.

Code-Behind: DisplayData.aspx.cs
csharp
using System;
using System.Threading.Tasks;
using YourProject.Helpers;

public partial class DisplayData : System.Web.UI.Page


{
protected async void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
// Define the Web API endpoint
string apiUrl = "https://jsonplaceholder.typicode.com/posts";

// Fetch JSON data


string jsonData = await ApiHelper.FetchJsonDataAsync(apiUrl);

// Process JSON data using LINQ


var processedData = JsonProcessor.ProcessJson(jsonData);

// Bind data to GridView


GridView1.DataSource = processedData;
GridView1.DataBind();
}
catch (Exception ex)
{
// Handle errors (e.g., display a message to the user)
Response.Write($"<script>alert('Error: {ex.Message}');</script>");
}
}
}
}

Example JSON Data

For the API https://jsonplaceholder.typicode.com/posts, the JSON response looks like


this:

json

[
{ "id": 1, "title": "Title 1", "body": "Body 1" },
{ "id": 2, "title": "Title 2", "body": "Body 2" },
{ "id": 3, "title": "Title 3", "body": "Body 3" }
]

You might also like