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) MVC.
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;
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action 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 returned to the view.
public class HomeController : Controller
{
public IActionResult Index()
{
//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");
List<Customer> customers = JsonConvert.DeserializeObject<List<Customer>>(json);
return View(customers);
}
}
View
HTML Markup
Inside the View, in the very first line CustomerModel is declared as Model for the View the ASP.Net TagHelpers are also inherited.
For displaying the records, MVC6 Grid is used.
The
WebGrid is initialized with the IEnumerable collection of
CustomerModel class object passed as parameter to the
Grid function of the
MVC6 Grid HTML Helper class.
@model IEnumerable<WebGrid_JSON_URL_Core.Models.Customer>
@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).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