Category Archives: JavaScript

Using jQuery with ASP.NET Core MVC

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

Then we did the reverse, retrieving data from the server (Using JavaScript with ASP.NET Core MVC (Part 2).

This time, we’re going to be doing it using jQuery.

What is jQuery?

Put simply, jQuery provides an easy and standardised way to manipulate the DOM (the elements on the webpage).

jQuery is ubiquitous. In web development it’s everywhere. Even with the rise of popular frontend frameworks such as Angular and React, jQuery isn’t going anywhere. Some devs might disagree, but as long as there are websites using JavaScript, jQuery will still be used. There’s a lot of code using jQuery, and if you’re not using a frontend framework you’ll most likely use jQuery with your JavaScript.

Here’s an example:

$("#searchbox").hide();

All this is doing is hiding an element named “searchbox”. jQuery is usually accessed via the “$” object (although it can be accessed using “jQuery” instead):

jQuery("#searchbox").hide();

But it’s far more powerful than that. This lets you hide all the elements that have the “canhide” class:

$(".canhide").hide();

And this lets you hide all the “div” elements on a page:

$("div").hide();

But you can do a whole lot more than just hide elements! To illustrate some of the things you can do: add attributes to elements, add/remove classes, modify CSS styles, create/delete elements.

Sure, you can do all of this – and more – using vanilla JavaScript. And if you’re just starting out, that’s a good way to improve your JavaScript skills. jQuery merely makes it all a lot easier, and handles browser differences and nuances for you.

jQuery also provides AJAX methods. Read on…

Sending Data to a Controller

Let’s jump right in and use jQuery to send some data to a controller in an MVC web application:

var name = $("#name").val();
$.post("/sayhello?name=" + name);

Here’s the equivalent JavaScript code:

var name = document.getElementById("name").value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "/sayhello?name=" + name);
xhr.send();

Of course, we need a controller action that handles the POST:

[HttpPost]
[Route("sayhello")]
public JsonResult SayHello(string name)
{
    var oldName = name_;
    name_ = name;
    return Json(new { name = oldName });
}

[FromBody]

If we don’t want to pass the name as part of the URL, we can pass the name in the request’s body.

First we’ll need to indicate that ‘name’ is coming from the request’s body, not the URL. Simply decorate ‘name’ with the FromBody attribute:

[HttpPost]
[Route("sayhello")]
public JsonResult SayHello([FromBody]string name)
{
    var oldName = name_;
    name_ = name;
    return Json(new { name = oldName });
}

And now we can send the request:

var name = $("#name").val();
$.post({
    url: "/sayhello",
    data: JSON.stringify(name),
    dataType: 'json',
    headers: {
        "Content-Type": "application/json"
    }
});

Here’s the equivalent JavaScript code:

var name = document.getElementById("name").value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "/sayhello");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(name));

Admittedly, the JavaScript code is a little shorter. But arguably the jQuery post() method is nicer to use and easier to read – you just pass an object containing key-value pairs.

Receiving Data from a Controller

Now we’ll use jQuery to request data from a controller:

$.get("/gettime", function (data) {
    $("#timeNow").text(data);
});

And here’s the equivalent JavaScript code:

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();

This time jQuery wins, hands down.

Conclusion

jQuery is very important in the world of web development.

You’re going to need to know it, because you’re guaranteed to use it.

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!

Using JavaScript with ASP.NET Core MVC

In the previous article (An Introduction to ASP.NET Core) I showed how an HTML form could be used to submit data to a controller.

This time, we’ll be using JavaScript and AJAX to asynchronously submit the data instead of using a form.

AJAX is the foundation of modern web applications. By using JavaScript and AJAX, the application – running on the client’s browser – can choose what data to send to the server, when to send it, and when to receive data from it.

A SPA (Single-Page Application) makes heavy use of AJAX in order to make the application appear as though it’s running locally, like a traditional installed application, rather than running on the internet or internal network. Users typically don’t navigate to other pages of the application; instead, only parts of the current page are updated when the user clicks something or when the page asynchronously receives new data.

What Does Asynchronous Mean?

In the simplest terms, a task executed ‘asynchronously’ means that the application continues to run without waiting for the task to complete. In JavaScript it’s common to specify a function that’s executed when the task eventually completes; these are callback functions.

Conversely, if the task executed ‘synchronously’ (note the ‘a’ missing from the start) then the application would wait for the task to complete and could appear to hang for a length of time; this might be acceptable if this was measured in milliseconds, but anything longer could be detrimental to the performance of the application.

Wherever possible, everything should be asynchronous.

What is AJAX?

AJAX (Asynchronous JavaScript and XML) is the technology that allows asynchronous communication between the client’s browser and the website’s server. (Ignore the XML in the name, it’s poorly named; most AJAX calls actually use JSON because it’s native to JavaScript.)

Fundamentally, AJAX works in pretty much the same way as normal web requests:

  • POST: data is sent to the server;
  • GET: data is retrieved from the server.

There are other verbs (actions) in common use too (including UPDATE and DELETE) and we’ll deal with these another time. In fact, right now we’re only concerned with POST…

Sending Data to a Controller

Let’s jump right in and send some data to a controller in an MVC web application:

var name = document.getElementById("name").value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "/sayhello?name=" + name);
xhr.send();

This is raw JavaScript that firstly gets the value of an input box, then creates and sends an AJAX request.

<div>
	<label>Your name is: </label>
	<input id="name" type="text" />
	<button id="sayHello">Say Hello</button></div>

Of course, we need an event that fires when the button is clicked:

var button = document.getElementById("sayHello");
button.addEventListener("click", function () {
	var name = document.getElementById("name").value;
	var xhr = new XMLHttpRequest();
	xhr.open("POST", "/sayhello?name=" + name);
	xhr.send();
}

Now we need a method on the controller that handles the POST request:

[HttpPost]
[Route("sayhello")]
public JsonResult SayHello(string name)
{
	var oldName = name_;
	name_ = name;
	return Json(new { name = oldName });
}

This simply stores the name in a private data member (name_) and returns the previous name.

[FromBody]

The above example sends the data as part of the URL. This is fine for a small number of simple parameters (strings, numbers), but not for complex objects. This is where the FromBody attribute can help:

[HttpPost]
[Route("sayhello")]
public JsonResult SayHello([FromBody]string name)
{
	var oldName = name_;
	name_ = name;
	return Json(new { name = oldName });
}

The controller method is identical aside for it’s declaration; the name argument has been decorated with the FromBody attribute. This means the name must be passed as part of the POST’s body:

var name = document.getElementById("name").value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "/sayhello");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(name));

We’re telling the request (via Content-Type) that we’re sending JSON-formatted data. We’re then using JSON.stringify() to convert (serialize) our object (name) to a string that can be transmitted with the request. ASP.NET Core will automatically deserialize the JSON retrieved from the request’s body.

Of course, we could pass a complex object as part of the request:

var data = {
	name: name,
	email: email,
	dateOfBirth: dateOfBirth
};
xhr.send(JSON.stringify(data));

The controller uses a single object, User, which would just be defined as a POCO with three properties (Name, Email, and DateOfBirth).

[HttpPost]
[Route("newuser")]
public JsonResult Receive([FromBody]User user)
...

Next Time

Next time we’ll be retrieving data from the server. Stay tuned, and keep safe.