How JSON is used in ASP.NET MVC? - C#

← Prev

In ASP.NET MVC, JSON (JavaScript Object Notation) is widely used to exchange data between the server and the client, especially when building dynamic web applications. Let's understand this.

Common Uses of JSON in ASP.NET MVC

Sending data to views: You can deserialize JSON data into a C# object or collection and pass it to the view using a model. For example, reading from a birds.json file and showing a list of birds.

Consuming APIs: MVC controllers can consume RESTful APIs that return data in JSON format. That data can then be bound to models and displayed.

AJAX calls: JavaScript or jQuery in your views can make AJAX requests to your controller actions. These methods can return JSON responses using JsonResult.

Reading a JSON File and Displaying It

Example:

This approach reads a local JSON file, converts its content into a list of objects, and sends it to a view for display.

🔹 JSON file (birds.json)

[
  { "ID": "001", "Name": "Eurasian Collared-Dove", "Type": "Dove" },
  { "ID": "002", "Name": "Bald Eagle", "Type": "Hawk" }
]

🔹 Model (modelBirds.cs)

public class modelBirds {
  public int ID { get; set; }
  public string Name { get; set; }
  public string Type { get; set; }
}

🔹 Controller

public ActionResult viewBirds() {
  string sJSONfile = Server.MapPath("birds.json");
  List<modelBirds> theBirds;
  using (StreamReader sr = new StreamReader(sJSONfile)) {
    var json = new JavaScriptSerializer();
    theBirds = json.Deserialize<List<modelBirds>>(sr.ReadToEnd());
  }
  return View(theBirds);
}

🔹 View

Finally, display the extract data using table.

<table>
  <tr><th>ID</th><th>Name</th><th>Type</th></tr>
  @foreach (var bird in Model) {
    <tr>
      <td>@bird.ID</td><td>@bird.Name</td><td>@bird.Type</td>
    </tr>
  }
</table>

← Previous