Filter and Display Data with ASP.NET Web Forms (Part 3)
Filter and Display Data with ASP.NET MVC (Part 1)

Filter and Display Data with ASP.NET Web Pages using Microsoft WebMatrix

In the previous three blog posts I’ve shown how to filter and display data with ASP.NET Web Forms. Now I’m doing the same with ASP.NET Web Pages. You will see how to filter and display data by using Microsoft Web Matrix, ASP.NET Web Pages, and Razor.

During the early days of ASP.NET there was a free tool named ASP.NET WebMatrix to create Web applications. This was at a time before there was a free edition of Visual Studio. Nowadays there’s an Express edition of Visual Studio that gives much more options than the old ASP.NET WebMatrix. Nowadays the name WebMatrix was reused for a new tool. The new tool, Microsoft WebMatrix ,makes it easy to start writing Web applications. A ton of predefined sites are available from the Web Gallery that can be taken as they are or adapted to specific needs. The predefined sites range from Blogs to CMS systems, eCommerce, Forums, Galleries, Tools, and Wiki. Often it’s not necessary to change the predefined sites, with many scenarios configuration is all what’s needed for adaption. The following figure shows a small part of the available sites.


For the small sample for this blog that does nothing than listing countries of F1 racers and displaying a list of racers for a selected country (the same sample as was done with ASP.NET Web Forms in the previous three blog entries) I’m starting with a simple site from a template: an empty site.


After creating the site the tool gives a view to the categories Site, Files, Databases, and Reports. Selecting the Site tab gives an entry point to the three other categories and also allows for publishing and looking for a hosting provider.

To create the sample, first a connection to the database is required. In the ribbon control of the tool Microsoft WebMatrix, in the section Database, a new connection to a database can be created. Clicking on the button New Connection opens the dialog as shown in the following figure. I’m creating the connection to the existing Formula1 database.


After the connection is created, the connection string is added to the file web.config:

<?xml version="1.0" encoding="UTF-8"?> <configuration> <connectionStrings> <add connectionString="Trusted_Connection=True;Server=(local);Database=Formula1" name="Formula1" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>

Next a page can be created. WebMatrix supports HTML, CSS, JavaScript files, and even PHP files can be created. I’m using the CSHTML file extension.


CSHTML files allow mixing server-side with the Razor syntax and client-side code within one file. The Razor syntax allows writing fewer characters for server-side code in contrast to ASPX. Scott Guthrie has a great blog post to introduce the Razor syntax.

On top of the page I’m declaring a few variables and open the database with the help of the Helper class Database. This class is defined within the namespace WebMatrix.Data The Database class is an adapter to ADO.NET to offer simple database requests. The Open method opens a connection to a database. Other methods are Query, QuerySingle, and QueryValue that are used on the instance of the Database class.

@{ var db = Database.Open("Formula1"); var selectedCountry = ""; var queryRacers = "SELECT Id, Firstname, Lastname, Country, Starts, Wins " + "FROM Racers WHERE Country = @0"; var queryCountries = "SELECT DISTINCT Country FROM Racers"; }

Helper classes make it easy to offer features from many different categories from Web applications. From the ASP.NET Web Pages Administration it is possible to install a lot of different helper classes as shown in the following figure. Helper classes are available to shorten URLs, to display Twitter widgets, connect to Windows Azure storage, search and buy within Amazon, add IE9 features to the Web application, do a Bing search, offer PayPal, and a lot more!


Then it’s easy to create a HTML select element with option children. Other than the first option, children are filled by invoking the foreach statement to iterate every item that is returned from the database query. The variable queryCountries is defined on the top of the page to make a distinct selection of all countries. With each item in the loop the Country property is used to display the country.

<select id="countrySelection" name="countrySelection"> <option>Select a country</option> @foreach (var item in db.Query(queryCountries)) { <option>@item.Country</option> } </select>

Running the application now, the list of countries is displayed as shown.


One might ask, how can there be a Country property with the result from the Query method. Contrary to the ASP.NET Web Forms sample from the last blog posts, here no Entity Framework mapping was done to create the entity and context classes. To tell the truth, there isn’t a Country property available. The Query method is defined to return IEnumerable<object>. In reality a list of DynamicRecord is returned. The type DynamicRecord is defined within the namespace WebMatrix.Data as well and derives from the base class System.Dynamic.DynamicObject. This makes use of dynamic features from .NET 4 and C# 4 to program with simple property style while in turn indexers are used.

To do a postback to the server on selection of an item, some JavaScript code and a form tag is needed. I’m adding this form element to the cshtml page around the select element. Submitting this form, a HTTP POST request is done to the file QueryF1Racers.cshtml.

<form action="QueryF1Racers.cshtml" method="post">

The request is started with the onchange event of the select element. The onchange event invokes the submit method of the first form element in the page.

<select id="countrySelection" name="countrySelection" onchange="document.forms(0).submit()">

Submitting a form to the server, values of the elements within the form can be retrieved with the Request object. In this code I’m setting the variable selectedCountry to the value that is returned from Request.Form[“countrySelection”]. countrySelection is the name of the select element.

@{ if (IsPost) { selectedCountry = Request.Form["countrySelection"]; } }

Now the selection within the select element should be corrected. After a postback the select element should have the same selection as was before the request. The option element that is a choice within the select element defines the selected attribute. If the value for this attribute is true, the choice is the selected one.

@foreach (var item in db.Query(queryCountries)) { if (item.Country == selectedCountry) { <option selected="true">@item.Country</option> } else { <option>@item.Country</option> } }

To display the list of racers for a specified country, I’m using the WebGrid class that comes with WebMatrix. The WebGrid class is defined within the namespace System.Web.Helpers. This class requires the source in form of  IEnumerable<Object> as the argument. This is created by invoking the Query method of the Database instance db. The Query method receives the SELECT statement to query for all racers from a specific country. The country parameter is passed with the second argument of the Query method. Finally, the GetHtml method of the WebGrid class returns HTML code.

@{ var grid1 = new WebGrid(db.Query(queryRacers, selectedCountry)); } @grid1.GetHtml()

Running the application now a country can be selected and a list of racers from that country is displayed.


The WebGrid returns an HTML table as shown from the output of the IE9 Developer Tools:


Using Microsoft WebMatrix and ASP.NET Web Pages is really easy. It’s not anymore the drag&drop style of programming as we’ve seen with ASP.NET Web Forms. With ASP.NET Web Pages you have to write a little code. However, using helper classes such as the Database and WebGrid classes this is not that hard. One big advantage of starting the development of Web applications with Microsoft WebMatrix and ASP.NET Web Pages is that all the doors are open to move to ASP.NET MVC.


CN innovation

The same functionality as shown here will be demonstrated with ASP.NET MVC in the next article of this series.

Here you can find the links to all articles from this series.


Feed You can follow this conversation by subscribing to the comment feed for this post.

django developer

scenarios configuration is all what’s needed for adaption. The following figure shows a small part of the available sites.

Links patrocinados

Greetings from Carolina! I'm bored to tears at work so I decided to check out your site on my iphone during lunch break. I really like the information you provide here and can't wait to take a look when I get home. I'm surprised at how fast your blog loaded on my mobile .. I'm not even using WIFI, just 3G .. Anyhow, wonderful blog!

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.


Post a comment

Your Information

(Name and email address are required. Email address will not be displayed with the comment.)