In this article I will explain with an example, how to populate (bind)
WebGrid using
JSON data from URL in ASP.Net Core (.Net Core) Razor Pages.
JSON File URL
The following API will be used in this article.
The API returns the following
JSON.
[
{
"CustomerId": 1,
"Name": "John Hammond",
"Country": "United States"
},
{
"CustomerId": 2,
"Name": "Mudassar Khan",
"Country": "India"
},
{
"CustomerId": 3,
"Name": "Suzanne Mathews",
"Country": "France"
},
{
"CustomerId": 4,
"Name": "Robert Schidner",
"Country": "Russia"
}
]
Model
The Model class consists of following properties.
public class CustomerModel
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Net;
using Newtonsoft.Json;
Index PageModel (Code-Behind)
Inside the PageModel, first a public property Generic List collection of Customer class is created.
The PageModel consists of following Handler method.
Handler method for handling GET operation
Inside this Handler method, first the Security Protocol is set.
Then, the
JSON string is downloaded from the URL using
DownloadString method of
WebClient class.
DownloadString method
It accepts the following parameter:
address – The URL of the file to be downloaded.
Then, the
JSON string is converted into a Generic List collection of
CustomerModel class object using
DeserializeObject method of
JsonConvert class.
Finally, the Generic List collection of CustomerModel class object is set to the public property of Customer Model class.
public class IndexModel : PageModel
{
public List<Customer> Customers { get; set; }
public void OnGet()
{
//Setting TLS 1.2 protocol.
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
// Fetch the JSON string from URL.
string json = new WebClient().DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json");
this.Customers = JsonConvert.DeserializeObject<List<Customer>>(json);
}
}
Razor Page (HTML)
HTML Markup
Inside the Razor Page, the ASP.Net TagHelpers is inherited.
For displaying the records, MVC6 Grid is used.
The
WebGrid is initialized with the
Customer Model class passed as parameter to the
Grid function of the
MVC6 Grid HTML Helper class.
@page
@model WebGrid_JSON_URL_Core_Razor.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@using NonFactors.Mvc.Grid;
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div id="Grid">
@(Html.Grid(Model.Customers).Build(columns =>
{
columns.Add(model => model.CustomerId).Titled("Customer Id");
columns.Add(model => model.Name).Titled("Name");
columns.Add(model => model.Country).Titled("Country");
})
)
</div>
</body>
</html>
Screenshot
Downloads