WebMatrix - A First Application

This article will take a first look at WebMatrix - Microsoft's new IDE for developing Web Pages applications. In it, I will cover a number of the core features that will make Web Matrix the ideal starter's web development framework as I create a very simple application.

NOTE

This article is based on WebMatrix Beta 1. Some items have changed in Beta 2, so the code may not run as-is. To check what has changed, please refer to this article: WebMatrix Beta 2 Changes

 

The web site I'm going to build will not do very much - it will simply display some books from a database. However, I will take a look at working with Sql Server Compact Edition within the WebMatrix IDE, the new Razor syntax, the new cshtml file type and some of the inbuilt helpers. I plan to look at more Web Pages features as I build on the functionality of the application over the course of additional articles. All of the code for this article is available as a download (link at bottom).

To start with, I need to create a site, so I start up WebMatrix, and choose Site From Template, then I select the Empty Site option. I save this as BookSite.

From this opening screen, we can manage files within the application, databases and SEO analysis of the site. For this example, I shall only be using the first two options. First, a database driven site needs a database, so clicking the Manage Databases link in the middle of the wscreen, or the Databases link in the left pane will get me to where I need to be. The next screen includes an invitation to add a new database:

By default, an App_Data folder is created, and within that, a database with the same name as the site. In this case, BookSite.sdf. I don't like that, so I would like to right click on the database and choose to rename it to Books. However, that is not an option in the Beta, so I have to choose Files in the left panel, and rename it from there once I have opened the App_Data folder. While I am in the Files View, I also delete the default index.html file, and add a new file called Default.cshtml, by either right clicking on BookSite and choosing New File, or by clicking the New option in the Files menu at the top of the workspace.

Going back the the Database view, I click the New Table button on the menu, and begin to add a table:

When finished, it has four fields and is saved as Authors:

I then add two more tables: Categories, and Books with the following definitions:

If I click the Data button on the main menu, I can start adding data directly to the tables:

OK. Now switching back to the File view, I open Default.cshtml, and at the top of the file, open a new code block with @{ }:

This is the new Razor syntax. The @ sign followed by a pair of braces denotes a multi-line code block, and could be thought of as equivalent to a non-code behind script runat="server" block. I'm going to test reading from the database, so I shall add some code to do that:

Database is a new class which provides an easy set of methods for working with databases. One of the methods - OpenFile() sets up a connection and opens the database whose file name is passed in to the method. The next line of code is a simple SQL query.

I add some more code to the body element of the page:

More Razor syntax: Database.Query() is a method that returns an IEnumerable<object>. The SQL is executed against the database, and the rows of data returned are converted into a collection of objects, with the database field names exposed as properties of those objects. foreach is preceded with an @ sign, but no braces. This is because there is only a single line of code. The literal text and html markup in the second line is not considered part of the code block, but it is recognised by the Razor parser as belonging to the each iteration of the loop, and the closing brace confirms that. Inline expressions or variables are also preceded by the @ sign, as in @row.Title. The Razor parser will recognise these and replace them appropriately. You can see from the shading in the image that the IDE recognises what is code and what is static html. We can see the result of this operation by clicking Launch in the menu, or simply hitting F12:

Looks fairly dull, so let's add some css to the site. Going back to the Files menu, if not already in it, I create a new folder called Styles by right-clicking on the site and choosing New Folder, and in that, I add a new file of type CSS. I leave that named as StyleSheet.css. In that, I add the following simple css rules:

This needs to be associated with the page, so I use one of the new helpers: Href(path), which creates a browser compatible URL from the local file name:

Notice again how the helper acquires a shaded background in the IDE. I amend Default.aspx to show more data:

Running this in the browser results in the desired effect...

...but also shows that some of the descriptions have typos in them. Entering data directly into a database is a pain, but I shall look at providing some editing functionality in a forthcoming article. In the meantime, some users of this application might not be interested in seeing such a wide ranging list of books. They may only be interested in seeing one category of books, so that's what I shall work on next.

The plan is to offer the user a category selection option prior to displaying books. They can either choose a category, or choose to see all books. As well as the title, author, ISBN and the description provided for each book, the category which the book belongs to will also be displayed. The first thing to do is to amend the existing SQL to bring in the additional data, and then to add some more to get the categories:

I need something to consume and display the categories so that the user can select one of them. An html select element fits this bill, and this goes at the top of the body area within the page:

At the moment, there are no helpers for the dropdown list, or select list. It is possible to template a helper to manage this kind of thing, but reusable code including helpers is something for a future article. The code is pretty simple to understand - a form tag is added, and within that, a select list with a default value hard-coded. From there, the result of the categories query is iterated to populate the option values and the display values for the select. Finally, a submit button is provided to post the form back, and the form itself is closed off.

There are some additional changes required. When the page first loads, I only want to display the select list and button. I will only show books when the user has made a selection and posted the form/page back. there are two options here - the user may choose the default one which will show all books, or they may decide to choose a particular category. If the default option is selected, the value passed to the server for CategoryID (the name of the select list) will be an empty string. If not, it will be a number. A helper function assists in identifying which it is - a number or not. The helper is IsInt(). You can see this being applied to Request["CategoryID"] in the code below, which only runs if the form has been posted - IsPost() is the property that helps determine that. The code that runs if the value is a number adds a bit to the SQL to be executed, including a parameter value for the CategoryId field in the database:

Parameter place holders need to be named in a certain way, starting with @0, then @1, then @2 and so on. Internally, the Database.Query() method will run through the collection of parameter values passed in and attempt to match them to a parameter placeholder based on their index within the collection. The index starts at 0, so names of placeholders is important, as is the order in which the parameter values are passed in. And finally, the code that runs to display the books is also wrapped in the IsPost() condition further down the page:

Here, the Database.Query() method is shown including a parameter value for the CategoryId value. If the SQL does not include the extra WHERE part because the user chose the default option, the Request["CategoryID"] value passed in is effectively ignored. There's no parameter placeholder to match it up with.

Finally, the last two images show the page as it first loads, and the result of selecting the Javascript category:

And that's it for now. While it's certainly no rival to Amazon, some of the new WebMatrix, Razor and Sql Server CE features have been covered. There are a lot of other features that haven't even been touched on, and I intend to experiment more with this new set of toys and publish the results as articles. The next article will examine how to provide a consistent look and feel for the site. In the meantime, the site files for this article, together with the database etc are available in the download. If you want to run it, get hold of WebMatrix and use the Site From Folder option once you have unzipped the download.