September 18, 2011

My first web pages application

I’ve used WebMatrix quite a few times since it was first released, but only for creating static web sites or ad-hoc editing of html/css. For everything else I’d jump into Visual Studio.

Excited by this video at BUILD that covers the new version of WebMatrix I thought I would finally have a go at writing a Web Pages site.

To begin with I just created a new site using the Photo Gallery template. This is actually a very good example to start with as it covers all the typical things you may want to do with a web application such as communicating with a database, posting forms, authentication etc.

ASP.NET Web Pages is like ASP.NET MVC without the controller (or Model View Presenter). That is, our server side code is inline within our view. For smaller applications this model is fine and personally I still prefer it to web forms.

After creating my site from the Photo Gallery template I added a new cshtml file. Next I opened “ASP.NET Web Pages Administration” (from the Site menu) and installed the OData package.

This package contains a helper for constructing OData requests. It also includes an example Netflix class that you can use to query the Netflix OData api.

I thought I’d create a Netflix search page, which turned out to be ridiculously easy:


    Page.Title = "Movies";
    if (IsPost) {
        Response.Redirect(Href("~/gallery/movies/", Request["title"]));
    var title = UrlData[0];
    // get matching movies or top action movies if empty search
    var query = title.IsEmpty() 
        ? Netflix.GetTopMoviesByGenre("Action & Adventure") 
        : Netflix.GetMoviesContainingWord(title);
    var movies = from m in query
            select new {
            Name = m.Name,
            ImageUrl = Netflix.GetMovieImage(m.Id)



<form action="" method="post">
        Search Movies:
        <input type="text" value="@UrlData[0]" name="title"/>
        <input type="submit" value"Search"/>

    @foreach (var movie in movies) {
            <img src="@movie.ImageUrl" alt="@movie.Name"/>

The page allows you to search for movies based on a title. Essentially we post the title back to the server, then redirect to the same page passing our title url parameter. This is a common approach for search pages and allows for searches via GET requests e.g. http://localhost:34231/gallery/movies/matrix

In WebPages you check for a form post using the “IsPost” property. We get access to the posted values via the “Request” dictionary.

Finally we make a call to the Netflix service storing the results in a variable that we can use in our page. This is done by simply iterating the collection using a “foreach” loop.

The result, a Netflix search page using ASP.NET Web Pages and Web Matrix:

Netflix search page with ASP.NET Web Pages

© 2022 Ben Foster