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.

Always Use Named Arguments

Consider a C# function call such as this:

string pathname = "...";
var lines = ReadLines(pathname, 10, true);

Is ReadLines() a poorly-designed function? Or is this just a bad function call?

If you’ve never seen the definition of ReadLines() before, you have no way of knowing what the three arguments represent just by looking at the function call. Granted, the first argument – pathname – is self-explanatory. But the other two arguments? It’s impossible to know or infer anything about them.

And when you’re reading (or debugging through) a lot of code, you really don’t want to have to rely on Intellisense (by hovering or pressing Shift+Ctrl+Space) or Peek Definition (Alt+F12) to figure out what such values mean!

Here’s the actual function declaration (contents omitted):

string[] ReadLines(string pathname, int maxLines, bool ignoreBlankLines)
{
    ...
}

And here’s how the function call can be improved:

string pathname = "...";
int maxLines = 10;
bool ignoreBlankLines = true;
var lines = ReadLines(pathname, maxLines, ignoreBlankLines);

But this is far too verbose! If you did this throughout your code base, it’ll significantly increase in size ūüė¶

JavaScript has a nice solution:

var lines = ReadLines({
    pathname: "...",
    maxLines: 10,
    ignoreBlankLines: true
});

Instead of passing individual arguments, you pass in a single object containing properties for the three values. (This allows values to be easily omitted, so obviously the function should perform validation of the object to ensure required values aren’t missing.)

It’s still a little verbose, but much more readable. And it could be condensed into one line:

var lines = ReadLines({ pathname: "...", maxLines: 10, ignoreBlankLines: true });

Named arguments in C#

But hang on a sec!

C# 4 (Visual Studio 2010) introduced ‘named arguments’:

string pathname = "...";
var lines = ReadLines(pathname, maxLines: 10, ignoreBlankLines: true);

Bingo! The reader of this code knows exactly what 10 and true now mean.

Instead of using named arguments, you could follow the JavaScript approach and put the parameters into an object:

class ReadLinesParams { ... }

string[] ReadLines(ReadLinesParams args) { ... }

var lines = ReadLines(new ReadLinesParams {
    pathname = "...",
    maxLines = 10,
    ignoreBlankLines = true
});

It’s not quite as easy as doing this in JavaScript because you have to define the ReadLinesParams class with properties for the three values.

Or you could create an anonymous type instead, and accept a dynamic argument:

string[] ReadLines(dynamic args) { ... }

var lines = ReadLines(new {
    pathname = "...",
    maxLines = 10,
    ignoreBlankLines = true
});

This has pros and cons, but by using ‘dynamic’ you lose both type safety and the ability of the code to document itself (i.e. how would somebody know what to pass into ReadLines() without looking at the function’s source code?).

Personally, I prefer and highly recommend the named arguments approach.

So, is this poor function design?

In terms of the original ReadLines() function at the top, not at all!

Function design – as with most aspects of software development – is subjective. Most would consider a function with 5 arguments as badly designed, others 10; but virtually everyone would consider a function with 20 arguments as badly designed! I’ll revisit this in a later post.

But calling a function with arguments that mean nothing to the reader (numbers and booleans especially), without using named arguments or an object? That can be considered poor programming that doesn’t help at all with debugging and maintenance.

A good guideline would be to always use named arguments, except where there’s no mistaking the purpose of an argument – e.g. File.Delete(“…”) – or where well-named variables are passed in as arguments – e.g. ReadLines(pathname, …).

Why Did I Create This Blog?

 

Why did I create this blog? If I’m honest, it’s down to one person: John Sonmez of Simple Programmer fame (https://simpleprogrammer.com).

If you’ve been listening to the .NET Rocks! podcast (https://dotnetrocks.com) for a while, it’s likely you’d have come across John Sonmez at some point. In a nutshell, and doing him a great injustice, he provides careers advice for software developers. To quote John himself, “Today, Simple Programmer is focused on helping software developers, programmers and other IT professionals improve their careers and live better lives.”

John has spoken – and posted – about creating your own ‘brand’, a professional online identity. That’s exactly what I’m attempting to do by creating this blog.

And to help, he’s created a short email course (https://simpleprogrammer.com/blog-course) that he’s providing for free.

In the course, he talks about

  • why a developer should create a blog;
  • what you should write about;
  • how to create a blog;
  • getting ideas for blog posts;
  • being consistent, posting regularly;
  • generating traffic for the blog.

A little while ago I realised I might have something useful to say (see my first blog post: Reinvention), so I followed the course and, with a little effort, here’s my blog. It’s very early days, but I’m here for the long-term. Thanks John!

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.

An Introduction to ASP.NET Core

ASP.NET Core uses .NET Core, and is the next generation of ASP.NET, having first been released only last year (2016).

ASP.NET itself uses the full .NET Framework, and has been around since .NET’s first release back in 2002.

In this article, I’ll provide a quick introduction to ASP.NET Core. If you already know about ASP.NET MVC, you won’t learn anything new here!

Note that I’ll use the term ‘web application’ rather than ‘website’, because web applications can be websites or web APIs, running either on the internet or on a private intranet. (A web API, if you’re unaware, can be considered a set of functions accessed across the internet or other network.)

Why .NET Core?

.NET Core – used by¬†ASP.NET Core,¬†naturally – is the next generation of the .NET Framework. It’s open source, cross-platform (Windows, Linux, Mac), highly performant, and getting better with every release. There’s virtually nothing bad anybody can say about it!

An Overview of MVC

You’ve almost certainly heard of MVC. In web development, it’s everywhere, and it’s not specific to ASP.NET, ASP.NET Core, or any other web technology.

Model-View-Controller (MVC) is an architectural pattern that splits an application into discrete parts according to their role. It’s not new, it’s been around for a long time, but it gained popularity particularly in the development of web applications.

Models

Models represent data. In an MVC application, there are two types of model: the model that represents data stored in database tables; and ‘view models’, which are used to transfer data to and from web pages.

Views

Views represent web pages, and web pages make up a web application. Users interact with views. Data (in the form of a view model) is passed to a view before it’s returned to the user’s browser, and passed back when the user submits a form.

Controllers

Controllers represent the logic behind a web application. When a user requests a web page, a controller picks up the request. The controller might perform some validation, processing, or other tasks, but ends by passing data (in the form of a view model) to a view. The view is then returned to the user’s browser.

Interaction

Here’s the obligatory diagram that shows the interaction between the parts of an MVC application:

MVC Architecture Diagram

It’s grossly simplified and high-level, but that’s the beauty of the MVC architecture: it is conceptually simple. If you’re coming from a Web Forms background, then MVC is radically different and adheres nicely to the separation of concerns (SoC) principle.

MVC Operations

Here’s a quick overview of how data is passed around in an MVC application.

Passing data to a view

The controller can trigger the rendering of a view by returning the result of calling the View() method. Any object can be passed to the view, and that object becomes the view model that the view uses to help render the HTML page.

public IActionResult Index()
{
    return View(new IndexViewModel
    {
        Name = "Dave"
    });
}

In this case the view model is actually a POCO (a class with no methods) defined as follows:

public class IndexViewModel
{
    public string Name { get; set; }
}

When a user navigates to the index page of the controller – e.g. http://example.com/controller/index or just http://example.com/controller – the controller’s Index() method is executed. This returns a View object (by default, it’ll return a view of the same name as the method; Index in this example). Optionally, a view model can be attached to the view, and the view (implemented using a .cshtml file) can use the data provided by the view model as simply as this:

Hello @Model.Name

At the head of the view (the .cshtml file) the view model must be referenced:

@model WebApplication1.Models.IndexViewModel

Sending data to a controller

There are (at least) two ways in which a page can send data to the page’s controller.

Forms

Typically, the user enters some text into an input control, then clicks a button which submits a form. The data is passed to the controller in the form of a view model.

<form action="/Home/Submit">
    <label>Your name is:</label> <input name="Name" type="text" />
    <button type="submit">Submit</button>
</form>

A method is added to the controller to handle the form submission:

public IActionResult Submit(IndexViewModel viewModel)
{
    return View(viewModel);
}

Remember that View() will cause a view (with the same name as the method unless specified) to be rendered.

Submit.cshtml must reference the view model at the top:

@model WebApplication1.Models.IndexViewModel

and the view model can be used:

Hello @Model.Name

(This is just the same as the Index view above!)

So the user enters their name in the text box, then presses Submit. The form’s action determines the controller (Home) and the page (Submit). So the HomeController’s Submit() method is called, with a view model created (from the contents of the form) and passed to the method. All our method does is return the view model, so that the Submit view can say hello.

There’s a lot going on here, and we’ve only just scratched the surface.

JavaScript

Another way in which data can be sent to a controller is by using JavaScript. But that’s beyond the scope of this short intro to ASP.NET Core. Maybe next time.

Sources of Information

There’s a lot of information on the internet, and finding good quality information can be hard.

So here’s a short list of websites, podcasts, and books that I frequently refer to. It’s not comprehensive, because it’s not meant to be!

Blogs/News

https://blogs.msdn.microsoft.com/dotnet
Everything .NET: new and upcoming releases, updates, and other useful articles.

https://blogs.msdn.microsoft.com/webdev
Web development using ASP.NET.

https://blogs.msdn.microsoft.com/visualstudio
New and upcoming releases of Visual Studio, plus details of patches, new features, and other useful articles.

https://code.visualstudio.com/blogs
News about Visual Studio Code.

https://www.smashingmagazine.com
Lots of good articles for web development and design.

https://www.reddit.com/r/webdev
Occasional links to useful articles and questions. It’s Reddit, what more can I say?

Podcasts

https://dotnetrocks.com
The original podcast for software developers, long before the word ‘podcast’ even existed. They talk everything .NET- and web-related, and a whole lot more. Lots of useful, good quality information.

https://hanselminutes.com
I’ve only recently started listening to this, but already I’m impressed by the quality of the information and the wide range of software development topics.

https://simpleprogrammer.com/2016/10/29/ultimate-list-developer-podcasts
As the link says, this is the ultimate list of developer podcasts. If you don’t like either of the above, you’ll certainly find something here.

Reference/Documentation

https://docs.microsoft.com/en-us/dotnet/core
Microsoft’s documentation for .NET Core. Written from scratch, bare in places, but getting better all the time.

https://docs.microsoft.com/en-us/aspnet
Microsoft’s documentation for ASP.NET Core. Includes guides and tutorials on getting started, and comprehensive references.

https://developer.mozilla.org/en-US/docs/Web
Mozilla’s comprehensive reference for everything web-related.

https://www.w3schools.com
An easy-to-use reference for everything web-related. Not as comprehensive as Mozilla, but provides info on everything that’s important.

Help

https://stackoverflow.com
The ultimate site for software developers. If you’ve got a problem, it’s pretty much guaranteed that somebody’s already encountered the same problem. Go here to find the solution!

https://answers.microsoft.com
Microsoft’s community for getting help with all sorts of problems with Microsoft’s technologies.

Training/Learning

https://www.pluralsight.com
Thousands of courses across a wide range of software development topics languages and technologies and other IT-related topics.

Books

Any self-respecting software developer should have a collection of books, whether they’re traditional paper books or modern e-books. Here’s a few selected books concerned with web development:

JavaScript: The Good Parts by Douglas Crockford (Yahoo Press / O’Reilly)
Essential reading, from the author of JavaScript! Tells you what’s good about JavaScript, and what to avoid.

JavaScript Patterns by Stoyan Stefanov (Yahoo Press / O’Reilly)
Shows you how to use JavaScript properly.

Responsive Web Design with HTML5 and CSS3 by Ben Frain (Packt)
How to layout modern web applications.

Pro ASP.NET Core MVC by Adam Freeman (Apress)
A good, albeit hefty book for developing web applications with .NET Core. If you’re new to the MVC pattern (model-view-controller) this does a good job at teaching the concept.