Creating Node.js Web Applications for ASP.NET MVC Developers

30 Aug 2017 18:26
Tags express nodejs vash

Back to list of posts

Overview

The transition from one programming language to another can often be a daunting task. However, Shawn Wildermuth put together a fantastic course on PluralSight called Node.js for .NET Developers that walks through step by step of how to create a Node.js web application from the perspective of an experienced ASP.NET MVC developer. I highly recommend that you watch the PluralSight course if you are interested in transitioning from ASP.NET MVC to Node.js. In this article, I will walk through creating a Node.js web application with Express and then making a few changes to give it a familiar feel to an ASP.NET MVC application.

Installing Node.js and Express

If you want to setup a "Production ready" environment with Node.js and Express, check out the article Create a Node.js Express Application on a CodeAnywhere Ubuntu 14.04 Container to set one up. However, if you just want to setup a web application for development, you can follow these directions:

  • Go to the Node.js Downloads page and download the appropriate Windows Installer for your platform (32-bit or 64-bit).
  • Run the Node.js Windows Installer on your machine.
  • From the Start menu, locate and click on the shortcut for "Node.js command prompt"
  • From the "Node.js command prompt" run the following command:
npm install express-generator -g

Creating and Running your first Express Application

Now that Node.js and Express are installed, you can create a Express application with these directions:

  • From the Start menu, locate and click on the shortcut for "Node.js command prompt"
  • From the "Node.js command prompt" navigate to the folder where you want to create an Express application run the following command:
npm install express-generator -g
  • Create an Express application with the following command: (Replace myapp with the name of the application you want to create.)
express --view=vash myapp
  • Change directories to the folder that the express generator created for your application and install the Node.js packages with the following commands:
cd myapp
npm install
  • Launch the application with the following command:
SET DEBUG=myapp:* & npm start

Changing Routes to Controllers

The Express application defines the routes in the routes folder. Each file in the routes folder processes an application end point. Express supports routing methods that correspond to HTTP meothds: get, post, put, delete…

In an ASP.NET application, controllers process the incoming requests. What we are going to do is replace the routes with controllers.

  1. Delete the (myapp)/routes folder.
  2. Create a (myapp)/controllers folder.
  3. In the controllers folder, create a JavaScript file called homeController.js
  4. In the (myapp)/controllers/homeController.js file, add the following code:
    (function (homeController) {
      // Define the init function to initialize all the routes for the home controller.
      homeController.init = function (app) {
     
        // If the route is "/" then show the index page.
        app.get("/", function (req, res) {
          res.render('index', { title: 'Express' });
        });
     
      };
    })(module.exports);
    

  5. In the controllers folder, create a JavaScript file called index.js
  6. In the (myapp)/controllers/index.js file, add the following code:
    (function (controllers) {
     
      // Get a reference to the home controller.
      var homeController = require("./homeController");
     
      // Initialize all the controllers.
      controllers.init = function (app) {
        // Initialize the home controller.
        homeController.init(app);
      };
     
    })(module.exports);
    

  7. In the (myapp}/app.js file make the following changes:
    1. Remove the following code to get the index and users routes on lines 8 and 9:
      var index = require('./routes/index');
      var users = require('./routes/users');
      

    2. Add the followiing code on line 8:
      var controllers = require("./controllers");
      

    3. Remove the following code to initialize the index and users routes on lines 25 and 26:
      app.use('/', index);
      app.use('/users', users);
      

    4. Add the following code on line 25:
      controllers.init(app);
      


* restart the application and then refresh the browser

Moving Views into folders

In an ASP.NET MVC application, a folder is created within the Views folder for each controller where all the views for the controller are placed. The Home controller has a /Views/Home folder and the Index.cshtml page is placed within that folder. We can implement the same folder structure in an Express application.

Create a home folder in the (myapp)/views folder. Move the (myapp)/views/index.vash file to the (myapp)/views/home folder.

In the (myapp)/controllers/homeController.js, change the location of the index view from index to home/index so that the homeController.js code looks like this:

(function (homeController) {
  // Define the init function to initialize all the routes for the home controller.
  homeController.init = function (app) {
 
    // If the route is "/" then show the index page.
    app.get("/", function (req, res) {
      res.render('home/index', { title: 'Express' });
    });
 
  };
})(module.exports);

* restart the application and then refresh the browser

Adding Client-side JavaScript Libraries with Bower

Bower is a package manager that can be used to add JavaScript libraries to the application. The advantage of using Bower is that it is easily installed, eliminates the need to find and download libraries and it has it's own json configuration file so that it doesn't conflict with the npm package manager used for the server side libraries.

Install Bower

To install bower, simply run the following command:

npm install -g bower

Configure bower

To install the client-side JavaScript libraries to the public/libs folder, a .bowerrc file need to be created to specify the public/libs folder as the location for all libraries downloaded by bower. Create a file called (myapp)/.bowerrc in the and paste the following into it:

{
  "directory": "public/libs/"
}

From the application folder (myapp), initialize bower by creating a bower.json file with the following command:
bower init

The bower init command will prompt you for values to be set in the bower.json file. To accept the default values, press [Enter].

Downloading bootstrap with Bower

To download bootstrap, navigate to your application folder, (myapp), and run the following command:

bower install bootstrap --save

Adding Bootstrap to the Application

Now that the bootstrap library has been added to the application, bootstrap can be used to create a nice Navigation Bar at the top of the page. In an ASP.NET MVC application content to be displayed on every page is added to the /Views/Shared/_Layout.cshtml view. Likewise in Express, content to be displayed on every page is added to the /views/layout.vash view. In the (myapp)/views/layout.vash view, add references to bootstrap and jQuery (a dependency that was downloaded with bootstrap) to the head block and then add the <nav> element to the body so that the contents of the layout.vash view looks like this:

<!DOCTYPE html>
<html>
<head>
  <meta>
  <title>@model.title</title>
  <link rel='stylesheet' href='/stylesheets/style.css' />
 
  <!-- Bootstrap -->
  <link rel="stylesheet" href="/libs/bootstrap/dist/css/bootstrap.min.css">
 
  <!-- jQuery -->
  <script src="/build/js/jquery.min.js"></script>
 
  <!-- Bootstrap -->
  <script src="/widgets/src/libs/bootstrap/dist/js/bootstrap.min.js"></script>
</head>
<body>
  <nav id="header" class="navbar navbar-inverse navbar-fixed-top">
    <div class="container-fluid">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand app-navigation-title" href="/">My App</a>
      </div>
      <div id="navbar" class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
          <li><a href="/home/about">About</a></li>
          <li><a href="/support/contactus">Contact Us</a></li>
        </ul>
      </div>
    </div>
  </nav>
 
  @html.block('content')
</body>
</html>

* refresh the browser

Adding the About View to the Home Controller

To add another view to a controller, open the controller JavaScript file and add another call to the app.get function to define a new route. Then add a new view for the About page in the views/home folder.

Adding the route to the Home Controller

Add the route to the About page in the Home Controller by adding a call to the app.get function where the first parameter defines a route of "/home/about" and the second parameter is a function that renders the "/view/home/about" view. Here is the code:

(function (homeController) {
  // Define the init function to initialize all the routes for the home controller.
  homeController.init = function (app) {
 
    // If the route is "/" then show the index page.
    app.get("/", function (req, res) {
      res.render('home/index', { title: 'Express' });
    });
 
    // If the route is "/home/about" then show the about page.
    app.get("/home/about", function (req, res) {
      res.render('home/about', { title: 'Express', createdBy: 'Your Name Here' });
    });
 
  };
})(module.exports);

Adding the About View

Create the about.vash file in the (myapp)/views/home folder. Add the following code to the (myapp)/views/home/about.vash file:

@html.extend('layout', function(model) {
  @html.block('content', function(model) {
    <h1>About @model.title</h1>
    <p>Created by: @model.createdBy</p>
  })
})

* restart the application and then refresh the browser

Add the Support Controller and Contact Us Page

To add the support controller, create the support controller in the controllers folder and initialize the support controller from the controllers/index.js file. Then add a support folder to the views folder and add the Contact Us view to the support folder.

Add the Support Controller

Create the supportController.js file in the (myapp)/controllers folder. Add the following code to the (myapp)/controllers/supportController.js file:

(function (supportController) {
  // Define the init function to initialize all the routes for the support controller.
  supportController.init = function (app) {
 
    // If the route is "/" then show the contactus page.
    app.get("/support/contactus", function (req, res) {
      res.render('support/contactus', { title: 'Express', email: 'support@myapp.com' });
    });
  };
})(module.exports);

Initialize the Support Controller

Call the supportController.init function from the (myapp/controllers/index.js file:

(function (controllers) {
 
  // Get a reference to the home controller.
  var homeController = require("./homeController");
 
  // Get a reference to the support controller.
  var supportController = require("./supportController");
 
  // Initialize all the controllers.
  controllers.init = function (app) {
    // Initialize the home controller.
    homeController.init(app);
 
    // Initialize the support controller.
    supportController.init(app);
  };
 
})(module.exports);

Add the Contact Us Page

Create a support folder in the (myapp)/views folder. Create the contactus.vash file in the (myapp)/views/support folder. Add the following code to the (myapp)/views/support/contactus.vash file:

@html.extend('layout', function(model) {
  @html.block('content', function(model) {
    <h1>About @model.title</h1>
    <p>Created by: @model.createdBy</p>
  })
})

* restart the application and then refresh the browser

References:

  1. Create a Node.js Express Application on a CodeAnywhere Ubuntu 14.04 Container
  2. Node.js for .NET Developers
  3. Express

Sample Code

Click to download sample code

Coming in September 2017

  1. Libraries to help Secure your Express Application
  2. Adding MongoDB and Mongoose to your Express Application

Comments: 0

Add a New Comment

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License