Using JavaScript with ASP.NET Core MVC (Part 2)

In the previous article (Using JavaScript with ASP.NET Core MVC) we asynchronously POSTed data from the browser to the server using JavaScript and AJAX.

This time, we’re going to asynchronously retrieve data from the server. The opposite of a POST request, is a GET request.

When you browse to a web page, the browser submits a GET request for that page. When you click on a link to another page, the browser submits another GET request. These are synchronous GET requests. They’re synchronous because the browser waits for the request to complete, and as a consequence the user also waits.

Asynchronous GET requests, on the other hand, happen ‘in the background’. They’re essential for modern websites that dynamically update only parts of a web page instead of reloading the page in full.

So a GET request is the retrieval of data, whether it’s a web page (synchronous) or whether it’s data of any other format via AJAX (asynchronous or even synchronous, although the latter is not recommended).

Retrieving Data from a Controller

Here’s how we can retrieve data from a controller:

var xhr = new XMLHttpRequest();
xhr.open("GET", "/gettime");
xhr.onreadystatechange = function () {
    if (xhr.readyState == XMLHttpRequest.DONE
        && xhr.status == 200) {
        //TODO
    }
};
xhr.send();

This is raw JavaScript that creates and sends a GET request. It’s asynchronous, because we’ve specified a callback function (by setting the onreadystatechange variable) that will be called only when the server returns a response.

We need something to trigger the GET request. This could be after a period of time has elapsed, or when a button is clicked. We’ll do the latter:

<div>
<div id="timeNow"></div>
<button id="getTime">Get Time</button></div>

When the button is clicked, the server responds with a single string that represents the current time (in UTC/GMT). Here’s the controller code that handles the request:

[HttpGet("gettime")]
public IActionResult GetTime()
{
    return Content(DateTime.UtcNow.ToString());
}

If we were returning something other than a string – such as an array or a complex object with properties – then we could return a JSON-formatted string instead. For our purposes though, a string will suffice here.

Here’s the full JavaScript that sends the GET request when the button is clicked, waits for the response, then writes the date and time to the webpage:

var button = document.getElementById("getTime");
button.addEventListener("click", function () {

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/gettime");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE
            && xhr.status == 200) {
            var div = document.getElementById("timeNow");
            div.innerText = xhr.responseText;
        }
    };
    xhr.send();

});

The response returns the string returned by the controller in the responseText member of the xhr object. Because we know it’s just a string, we can set the timeNow div’s inner text to the string value (the date and time).

That’s all there is to it!

One thought on “Using JavaScript with ASP.NET Core MVC (Part 2)

  1. Pingback: Using jQuery with ASP.NET Core MVC | A blog for software developers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s