Introduction to ASP.NET Web Pages and Razor Syntax

 

What are ASP.NET Web Pages or Razor Syntax?

ASP.NET is a lightweight, fast and simple technology for creating dynamic web content. Dynamic web content consists of a combination of front-end technologies (e.g. HTML 5, CSS 3 & JavaScript) and server technologies (ASP.NET Web Pages, Razor Engine). This merging makes internet pages or internet applications possible which access databases, carry out server-side checks and logic, send e-mails or also request other web services.

In addition, Microsoft supplies numerous “helpers” which represent small extensions for various application areas of the ASP.NET Web Pages. The current ASP.NET Web Helpers Library therefore includes “helpers” for the following topics:

Authentication & Authorization
Captcha Validation
Twitter Profile & Search
Gravatar Images
Bing Search
and much more…

 

What is the difference to other ASP.NET technologies?

The ASP.NET technology stack contains other technologies that can also be used to create dynamic websites. Below is a list of the underlying focus:

ASP.NET Web Forms : is based on the classic Windows interface programming (Windows Forms), thus contains similar controls (button, checkbox, list, …) and is based on an event-based interaction. The switch should be as small as possible for programmers who have developed Windows Forms. Many aspects of the display (HTML, CSS, …) are highly abstracted, so that when suitable controls are used, there are only a few points of contact with classic web client technologies.
ASP.NET MVC: focuses heavily on the separation of concerns and the testability of the software system. To achieve this, the Model-View-Controller pattern is implemented, which ensures a separation between logic, data and presentation. The client logic is only slightly abstracted, the focus here is on individualization and a wide range of functions, so that in-depth knowledge of web client technologies (HTML 5, CSS 3, JavaScript) is often necessary.

Together with the ASP.NET Web Pages, these three technologies offer the portfolio for web development from Microsoft. All three are also being further developed by the same team, so that many basic technologies can be found in all of them or there are numerous overlaps.

The choice of which technology to prefer depends heavily on the future application area of the Internet application, as well as the prior knowledge and experience of the development team. ASP.NET Web Pages is particularly useful if the development team has not previously worked with other ASP.NET technologies and is more likely to have a background in pure web client development. It can also make sense to use ASP.NET Web Pages if a website has only little dynamic content and the majority is static.

This is the case, for example, on many company websites that do not publish dynamic product catalogues, but only the contact form is a dynamic component. This is exactly why we look at this together in the example.

Razor Syntax

Before we can turn to the example (tutorial) together, we need to understand what the Razor syntax offers and what it can be used for.

Server-side code fragments can be embedded in HTML code using the Razor syntax. These fragments can exist both in C# and in Visual Basic – however, we will only use C# here. The Razor Engine parses this syntax and executes the code it contains. The most important elements are as follows:

@{ var count = 7; }
@{ var messageTitle = “Hello World”; }

@{
var today = DateTime.Now;
var welcomeMessage = “Today is ” + today;
}

This is your @count visit
Welcome: @welcomeMessage

Everything else will be done at the respective Point explained within the tutorial.

Tutorial: Contact Form

To show the whole thing with an example, we will now create a contact form together. This also has a practical effect: almost every website needs this or wants to offer this. In addition, we can look at different things in one go:

layouts
server-side validation of inputs
server-side logic for reading form fields
server-side sending of a Email

 

Create layout

First we need to create a new project within WebMatrix: New > Empty page. Then we create a file with the layout.

What is a layout? A layout defines the basic structure of a website. Within a layout, it is often defined where and how the navigation, the header, the footer and of course the content area is displayed. For the sake of simplicity, we’re going to use something very simple as our layout:

@Page.Title

 

My tutorial

@RenderBody()

© @DateTime.Now.Year My Tutorial

You guys fall Razor syntax elements certainly appear in three places:

@Page.Title: At this point, the content of the title property is output on the page object.
@RenderBody(): This is a very important element in layout: it defines where the content area should be rendered.
@DateTime.Now.Year: The current year is output.

We now save this file as “_Layout.cshtml”.

Now we create the page for our contact form: “Contact.cshtml”.

To use the layout functionality, we write the following lines in this file:

@{
Layout = “~/_Layout.cshtml”;
}

Contact

Using the layout definition, we specify which layout file should be used for display. The Razor engine then takes that file, looks for “@RenderBody()” and renders the actual output there.

My tutorial

 

Contact

© 2013 My Tutorial

 

Create HTML contact form

Let’s create a simple form to fill in some information. It is important to specify the name attributes so that the input fields can then be read out on the server side:

@{
Layout = “~/_Layout.cshtml”;
}

Contact

Contact details

Name:
Email address:

Message

Subject:
Content:

 

Server-side reading of the input fields

We can easily read the input fields in our code. Before that, however, we still check whether the request was sent via POST. Simply loading the page leads to a GET request, clicking on the submit button by specifying method=”post” leads to a POST request.

@{
Layout = “~/_Layout.cshtml”;

var name = “”;
var mail = “”;
var title = “”;
var message = “”;

if(IsPost){
name = Request.Form[“name”];
mail = Request.Form[“mail”];
title = Request.Form[“title”];
message = Request.Form[“message”];
}
}

Contact

Server-side verification of the data

To check the input fields, we use a built-in validation helper from the ASP.NET Web Pages – no additional NuGet package is therefore necessary.

Validation rules can be created using simple static methods and their validity can be queried later. There are also helpers for displaying validation errors:

@{
Layout = “~/_Layout.cshtml”;

Validation.RequireField(“name”, “A name is required.”);
Validation.RequireField(“mail”, “Your email address is required.”);
Validation.RequireField(“title”, “A title is required.”);
Validation.RequireField(“message”, “A message is required.”);

var name = “”;
var mail = “”;
var title = “”;
var message = “”;

if(IsPost)
{
if(Validation.IsValid())
{
name = Request.Form[“name”];
mail = Request.Form[“mail”];
title = Request.Form[“title”];
message = Request.Form[“message”];
}
}
}

Contact

@Html.ValidationSummary()

Contact details

Name: @Html.ValidationMessage(“name”)
E -Mail address: @Html.ValidationMessage(“mail”)

Message

Subject: @Html.ValidationMessage(“title”) < br />Content: @Html.ValidationMessage(“message”)

 

Send an email

There are also built-in helpers for sending e-mails, which make your life easier. The WebMail class was added for this purpose. After some SMTP server information, e-mails can simply be sent:
no-repeat;left top;;
auto

@{
Layout = “~/ _Layout.cshtml”;

Validation.RequireField(“name”, “A name is required.”);
Validation.RequireField(“mail”, “Your email address is required.”);
Validation.RequireField(“title”, “A title is required.”);
Validation.RequireField(“message”, “A message is required.”);

var name = “”;
var mail = “”;
var title = “”;
var message = “”;

if(IsPost
&& Validation.IsValid())
{
name = Request.Form[“name”];
mail = Request.Form[“mail”];
title = Request.Form[“title”];
message = Request.Form[“message”];

WebMail.SmtpServer = “SMTP host”;
WebMail.SmtpPort = 25;
WebMail.UserName = “user-name”;
WebMail.Password = “password”;
WebMail.From = “info@website.de”;

WebMail.Send(to: WebMail.From,
subject: “Contact Form: ” + title,
body: name + ” ” + mail + ” ” + message < br />);
}
}

Contact

What’s still missing?

Of course, the productive code is still missing a bit – including:

CSS design
Further checks, e.g. on the client side, valid e-mail Address, …
Installation of Captchas against SPAM
Catching errors
Display of a shipping confirmation

 

More information.

More information, numerous explanations, an introduction, tutorials and video exercises can be found on the official website https://dotnet.microsoft.com/en-us/apps/aspnet/web-apps. The 9-part tutorial for beginners is particularly recommended: https://dotnet.microsoft.com/en-us/apps/aspnet. For example, the following topics are discussed here:

Database access
Tabular data representation
Deployment

Mit Centron Colocation: Sicherheit und Effizienz für Ihre IT-Infrastruktur

Create a Free Account

Register now and get access to our Cloud Services.