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.

image

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.

image

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.

image

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.

image

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!

image

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.

image

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.

image

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

image

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.

Christian

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.