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:
[Link]
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 [Link] Core
Step 1: Create a New [Link] Core Project
1. Open Visual Studio and select File > New > Project.
2. Choose the [Link] 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: [Link]
This service will handle HTTP requests to the Web API.
using [Link];
using [Link];
namespace [Link]
{
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 ([Link])
{
return await [Link]();
}
throw new HttpRequestException("Failed to fetch data from the API.");
}
}
}
Step 3: Process and Query JSON Data Using LINQ
Use [Link] to parse and query JSON data.
Code: [Link]
This class parses JSON and queries it using LINQ.
using [Link];
using [Link];
using [Link];
namespace [Link]
{
public static class JsonProcessor
{
public static List<dynamic> ProcessJson(string jsonData)
{
var jsonDocument = [Link](jsonData);
var jsonArray = [Link]();
return jsonArray
.Select(item => new
{
Id = [Link]("id").GetInt32(),
Title = [Link]("title").GetString(),
Body = [Link]("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 [Link];
using [Link];
using [Link];
namespace [Link]
{
public class DataController : Controller
{
private readonly ApiService _apiService;
public DataController(ApiService apiService)
{
_apiService = apiService;
}
public async Task<IActionResult> Index()
{
string apiUrl = "[Link]
string jsonData = await _apiService.GetJsonDataAsync(apiUrl);
var processedData = [Link](jsonData);
return View(processedData);
}
}
}
Razor View
Create a Razor View [Link] 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>@[Link]</td>
<td>@[Link]</td>
<td>@[Link]</td>
</tr>
}
</tbody>
</table>
Implementation in [Link] Web Forms
Step 1: Fetch JSON Data Using HttpClient
Code: [Link]
Use HttpClient to fetch JSON data.
using System;
using [Link];
using [Link];
namespace [Link]
{
public static class ApiHelper
{
public static async Task<string> FetchJsonDataAsync(string apiUrl)
{
using (HttpClient client = new HttpClient())
{
var response = await [Link](apiUrl);
if ([Link])
{
return await [Link]();
}
throw new Exception("Error fetching JSON data.");
}
}
}
}
Step 2: Parse JSON Data Using LINQ
Code: [Link]
Process JSON using [Link].
using [Link];
using [Link];
namespace [Link]
{
public static class JsonProcessor
{
public static List<dynamic> ProcessJson(string jsonData)
{
var jsonArray = [Link](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 [Link];
using [Link];
public partial class DisplayData : [Link]
{
protected async void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string apiUrl = "[Link]
string jsonData = await [Link](apiUrl);
var processedData = [Link](jsonData);
[Link] = processedData;
[Link]();
Sample JSON API
The API [Link] 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 [Link] Web Forms
1. Setup the [Link] Web Forms Project
1. Create a new [Link] Web Forms project in Visual Studio.
2. Add a new Web Form (e.g., [Link]).
2. Fetch JSON Data Using HttpClient
You can use HttpClient to fetch the JSON data from the Web API.
Code: [Link]
Add a helper class to fetch JSON data.
using System;
using [Link];
using [Link];
namespace [Link]
{
public static class ApiHelper
{
public static async Task<string> FetchJsonDataAsync(string apiUrl)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await [Link](apiUrl);
if ([Link])
{
return await [Link]();
}
throw new Exception("Error fetching JSON data.");
}
}
}
}
3. Parse and Process JSON Using LINQ
Use [Link] or [Link] for parsing JSON. For simplicity, we'll use
[Link].
Code: [Link]
Add a helper class to parse JSON and process it using LINQ.
using [Link];
using [Link];
namespace [Link]
{
public static class JsonProcessor
{
public static List<dynamic> ProcessJson(string jsonData)
{
var jsonArray = [Link](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 [Link] file, add a GridView control.
Markup: [Link]
html
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]" %>
<!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 [Link] file, fetch the JSON data, process it using LINQ, and bind it to the
GridView.
Code-Behind: [Link]
csharp
using System;
using [Link];
using [Link];
public partial class DisplayData : [Link]
{
protected async void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
// Define the Web API endpoint
string apiUrl = "[Link]
// Fetch JSON data
string jsonData = await [Link](apiUrl);
// Process JSON data using LINQ
var processedData = [Link](jsonData);
// Bind data to GridView
[Link] = processedData;
[Link]();
}
catch (Exception ex)
{
// Handle errors (e.g., display a message to the user)
[Link]($"<script>alert('Error: {[Link]}');</script>");
}
}
}
}
Example JSON Data
For the API [Link] 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" }
]