Frequently I see devs needing to make calls into C# controllers and return some data to the front end. The most common tool I’ve seen these devs reach for is the jQuery $ajax wrapper.

I asked the question: “Can this be done without jQuery?” And, overwhelmingly, the answer I got back was no. I didn’t think that made a lot of sense since jQuery is really just using JavaScript under the hood. So it would seem that you must be able to achieve this with plain old js.

After a bit more digging, I found that it is possible. Here’s how:

Let’s assume we have Hello World being sent to us from the controller, and then we want to show it in an alert. Our front end won’t know what is going to be displayed until it is returned from the controller. Our controller method might look like this:

  [HttpGet]
  public ActionResult RespondToAjax()
  {
      return Json("Hello World!", JsonRequestBehavior.AllowGet);
  }

Things to note here are that we’ve added the [HttpGet] decorator above our method, thus denoting that this is a get and not a post. Also, with the JSON string we’re returning, we added JsonRequestBehavior.AllowGet. Without this you’ll get an error because MVC doesn’t just allow gets willy-nilly.

Our js function might look like this:

function callCtrler() {
    var req = new XMLHttpRequest();
    req.open('GET', '@Url.Action("RespondToAjax", "Home")', true);
    req.setRequestHeader('Content-Type', 'application/json');

    req.onload = function () {
        if (req.status >= 200 && req.status < 400) {
            alert(req.responseText);
        } else {
            alert('We encountered an error!');
        }
    }

    req.send();
}

One thing I want to note here is that we are using razor with @Url.Action. It’s important to use @Url.Action over a relative path (./file/path/) because relative paths won’t always work in MVC. Using the above method won’t allow you to move your javascript into its own file. However, you can attach the @Url.Action to an element with a data attribute and access it that way.

<form id="myForm" data-ctrl-url='@Url.Action("RespondToAjax", "Home")'></form>

Then in your JavaScript you can use:

var ctrlUrl = document.getElementById('myForm').getAttribute('data-ctrl-url');

Now let’s look at how we might do a POST. We’ll need both a controller method and a class this time.

[HttpPost]
public ActionResult PostFromAjax(TestModel postParams)
{
    // do something with data, probably create db record
    return Json("Success!");
}

public class TestModel
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string FavoriteColor { get; set; }
}

We have our action method using [HttpPost] as the decorator this time. This allows us to post to the method. We also created a class for the data. You aren’t able to use built in types such as Dictionary or object, so you’ll need to create a custom class for the data to map to.

Now let’s take a look at what the js function looks like.

function postToCtrl() {
    var tmpObj = {
        Name: 'Carmen',
        Age: 26,
        FavoriteColor: 'Green'
    };

    var req = new XMLHttpRequest();
    req.open('POST', '@Url.Action("PostFromAjax", "Home")', true);
    req.setRequestHeader('Content-Type', 'application/json');
    req.send(JSON.stringify(tmpObj));
}

Notice we made an object with the exact same properties as our class – this allows the data to be mapped to the class properly. We also stringified the data before sending it across.

And there you have it! GET and POST to C# methods without jQuery!

Checkout the test app I made for this.

Questions? Tweet me!

Sign up for blog updates!

* indicates required

In this post we’ll go through the step-by-step process of setting up a headless Raspberry Pi. The best part is, you can do all of this from a secondary computer, so you have no need for a monitor or keyboard and mouse!

1. Purchase a Raspberry Pi, power supply, and micro SD card.

This probably seems pretty obvious, but make sure you get a micro SD card, with a minimum of 16gb of storage. Don’t forget the power supply like I did, because those can be hard to find later on.

You can get all of these things on Amazon, or get them in all together in a kit (also from Amazon).

2. Download a Raspian system image from raspberrypi.org.

You don’t have to use Raspian, but I like to stick with this – especially as I’m getting started.

3. Use etcher to copy the system image to your SD card.

Etcher makes it super easy to copy the system image to your SD card.

4. Create an empty ssh file in the root directory

While still on your computer (not the raspberry pi), cd into the root directory of the SD card and use: touch ssh. This will generate an ssh file, which will allow you to ssh into your raspberry pi.

5. Generate a wpa_supplicant.conf file

While still in the root directory, create a wpa_supplicant.conf file with: touch wpa_supplicant.conf. Then use: nano wpa_supplicant.conf. While in this file, create a network object like so:

network={
  ssid="testing"
  psk="testingPassword"
}

where ssid is the name of your network, and psk is your password.

** Extra credit: use a passphrase to encrypt your password. **

6. Insert the SD card into the pi and plug it in.

You’re ready to go!

You’re now ready to ssh into your raspberry pi from another computer and use your pi via the command line. No monitor, keyboard or mouse required!

** Extra credit: Change the hostname of Raspberry Pi **

** Extra credit: Set up a shortcut to easily ssh into your pi. **

Questions? Tweet me!


If you are using a headless setup for your Raspberry Pi, you can easily set up a wpa_supplicant.conf file to connect to wifi. But it is very important to mask your password for security reasons. In this post, I will show you how.

Your wpa_supplicant.conf file has network objects that look like this:

network={
    ssid="testNetwork"
    psk="testingPassword"
}

Where ssid is your network name and psk is your password. But you’ll notice that that is just a plain text password, which we all know is a no-no.

Use this command: wpa_passphrase [ssid-name] [password-name] and be sure to wrap the network and/or password in quotes if you have spaces in either.

This command will spit out a new network object that looks like this:

network={
	ssid="testNetwork"
	#psk="testingPassword"
	psk=575827beef2c7dbdcf817a9cd0e6b96fb0fd3f54e2c0fbf24a38eb04fb7e9aa3
}

Copy this and use sudo nano /etc/wpa_supplicant/wpa_supplicant.conf and add this new network object to the file, or edit the old network object with the new passphrase. Just be sure to delete the commented-out plain text password from the file before you save it.

You can use the iwgetid command to confirm which network you are connected to. And you’re good to go!

Questions? Tweet me!

Sign up for blog updates!

* indicates required

If you are using ssh shortcuts for your Raspberry Pi, it can be a good idea to give each pi you set up a unique hostname. If you are using the raspian distribution from raspberrypi.org, raspberrypi.local is the default hostname.

Since IP addresses can change, it’s not good to use this in your ssh config file. So instead, I’ll show you how to change the hostname to be unique on each different pi.

First, while ssh’d into the pi, use: the hostname command. This will show you what the current hostname of the pi is.

Next use sudo nano /etc/hosts and change the hostname in that file. (It’s listed next to the IP address.)

Then use sudo nano /etc/hostname and change the hostname in this file.

Lastly, use reboot to restart the pi and ssh back in using the new hostname and voila!

Questions? Tweet me!

Sign up for blog updates!

* indicates required

If you are ssh-ing into your Raspberry Pi, it can be a real pain to find and remember the IP address for the machine. This shortcut makes it easy, because you no longer need to remember!

On the computer you use to ssh into the pi, use: nano ~/.ssh/config to open the config file in your ssh directory. (If you don’t have one of these use touch ~/.ssh/config to create one, and then use nano to edit it.)

Use the following:

Host myPi2
        Hostname 192.168.2.45
        User pi

You can use either the hostname of the Pi or the IP address for the hostname (use: hostname in the terminal of your Pi to find the hostname or PiFinder to find the IP address).

You’ll use whatever username you usually use to log in for User.

You can swap myPi2 with whatever shortcut you’d like to use to ssh in. For the above example, I would use: ssh myPi2 to gain access to the pi, and I would then be prompted for my password.

Questions? Tweet me!