For Nancy, I have heard about it in .NET Rocks and Hanselminutes podcasts for a while, but I haven’t had a chance to look at it until recently. Basically, Nancy (or NancyFX) is a lightweight web framework allowing you to build HTTP based web applications or services using .NET. Nancy is very easy to learn and set up.However, It doesn’t depend on System.Web and doesn’t need to be run on IIS at all. Most importantly, Nancy is very easy to learn and set up as you will see.
Using them together makes our job to create a web app much easier.
Ok. Enough with the background. Let’s get start by building a web app using Durandal and Nancy (I will touch on Bootstrap once we have a web app running).
First, we start with just an empty ASP.NET web site.
Once we have the web site project, we install Durandal and Nancy via NuGet. Since I want our web app to run on IIS, I also have another package, Nancy.Hosting.Aspnet installed.
If everything went smoothly, you should see these packages installed in your project. As Durandal is using JQuery, Knockout, and RequreJS, those packages will be installed as well.
Now, let’s start coding. We start in the client-side by creating modules (viewmodels) and views. If you have played with the Durandal StarterKit, you should be familiar with the files (index.html, main.js, shell.js, etc.). I won’t explain what those files do here, but you can find more information about them here.
Next, we look at the server-side with Nancy. To set up a Nancy site, what I need to do is to create a C# class derived from NancyModule, and define route handler in the constructor. We don’t need to worry about the name. As long as it is derive from NancyModule, Nancy will find it. Here is how I want Nancy to return back index.html for the root URL.
Here is how our project looks right now.
Now, let’s run the web app. And you should see our very simple web app
To make our web app a bit less trivia, I will add another Durandal view and module which will do some AJAX call to get JSON data from the server. Here is the code in the new module.
The page is expecting the server to send JSON when it hits /api/list. With Nancy, we can do that easily by adding just couple lines of code.
Now. let’s run our web app again and click the new link!
Wow! super easy, right?
So far, we just have our client-side and server-side code taken care. However, you probably notice that our web app doesn’t look good at all. This is how Bootstrap can help. By using its reusable CSS templates, we can make our web app looks much better with ease.
Before we can do that we have to install Bootstrap package.
Let’s run our web app again.
That’s it. Using Durandal, Nancy, and Bootstrap, we have a super-duper-happy SPA web app done right! 🙂