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.

2 thoughts on “Using JavaScript with ASP.NET Core MVC

  1. Pingback: Using JavaScript with ASP.NET Core MVC (Part 2) – A blog for software developers

  2. 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