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.

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