jQuery getJSON Example in ASP.NET MVC


Simple jQuery getJSON Example in ASP.NET MVC

Definition and Usage

The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

Syntax

$(selector).getJSON(url,data,success(data,status,xhr))
ParameterDescription
urlRequired. Specifies the url to send the request to
data Optional. Specifies data to be sent to the server
success(data,status,xhr) Optional. Specifies the function to run if the request succeeds
Additional parameters:
  • data - contains the data returned from the server.
  • status - contains a string containing request status ("success", "notmodified", "error", "timeout", or "parsererror").
  • xhr - contains the XMLHttpRequest object

In this post, I will create a very basic and simple example demonstrating
jQuery's getJSON method using ASP.NET MVC.

First up, I create an empty MVC project with one Controller. The code for this 

controller is shown below. For simplicity, the data model is also stored here and 
we create the data on fly. In a production application, this will be separated using 
multiple layers and the data, of course, would come from the database.

Create a New MVC3 Project => named getJsonDemo2.

Create a Model Class Named getJsonModel.cs :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace getJsonDemo2.Models
{
    public class getJsonModel
    {

    }
    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public List<Address> Addresses { get; set; }
    }

    public class Address
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string ZipCode { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    }
}

In HomeController.cs Add the Following Code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using getJsonDemo2.Models;

namespace getJsonDemo2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public JsonResult GetJsonData()
        {
            var persons = new List<Person>
                              {
                                  new Person{Id = 1, FirstName = "F1", 
                                      LastName = "L1", 
                                      Addresses = new List<Address>
                                                      {
                                                          new Address{Line1 = "LaneA"},
                                                          new Address{Line1 = "LaneB"}
                                                      }},
                                                                                                        
                                  new Person{Id = 2, FirstName = "F2", 
                                      LastName = "L2", 
                                      Addresses = new List<Address>
                                                      {
                                                          new Address{Line1 = "LaneC"},
                                                          new Address{Line1 = "LaneD"}
                                                      }}};

            return Json(persons, JsonRequestBehavior.AllowGet);
        }
    }
}

This controller has just 2 actions. The Index action has a view associated with it 
and that view contains a button which will fire a JSON request. That request would 
be handled by the GetJsonData action method. As you can see, our data model is 
pretty simple and it contains a list of persons and each person can have multiple 
addresses. The Index view contains just a button and an empty div tag in the
beginning. The javascript code block contains the click handler for this button. 
When this button is clicked, we use the getJSON method to call the GetJsonData 
action. Once this data is returned we use the .each() jQuery method to loop through
each person and then through each address and append some of their properties to
the div tag. Code for Index view and the output when we click on the button is 
shown below.

In Index.aspx add the Following Code

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: ViewBag.Message %></h2>
    <input id="btnGetPersons" type="button" value="Get Persons" />
<div>
    <div id="ajaxDiv">
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $('#btnGetPersons').click(function () {
            $.getJSON("/Home/GetJsonData", null, function (data) {
                var div = $('#ajaxDiv');
                div.html("<br/> " + "Persons received from server: " + "<br/>");
                $.each(data, function (i, item) {
                    printPerson(div, item);
                });
            });
        });
    });

    function printPerson(div, item) {
        div.append("<br/>" + "FName: " + item.FirstName + ", LName: " + item.LastName);
        $.each(item.Addresses, function (i, addr) {
            printAddress(div, addr);
        });
    }

    function printAddress(div, item) {
        div.append("<br/>" + "   " + "Line1: " + item.Line1);
    }
</script>
</asp:Content>

The output looks like: 
In the getJSON method we can pass parameters as well. For ex, if we had to pass the number of persons to retrieve, we could have passed something like {count:"5"} instead of null and then in the action method we could have changed the GetJsonData() method to GetJsonData(int count).


1 comment:


  1. Im no expert, but I believe you just made an excellent You certainly understand what youre speaking about, and I can truly get behind that.
    Regards,
    Angularjs training in chennai

    ReplyDelete

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (17) Entity Framework (3) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives