Tuesday, July 8, 2014

Razor for the web (HTML rendering)

Razor is a type of syntax combining content with code. Essentially, its nothing new, and uses the same concepts from .NET code languages and HTML. If you can do those, then it is simple to implement Razor onto your website to make certain features easier to add and use. All razor is processed and removed on the server before the page is posted to the browser for the user. Thus, users do not see it (even the comments and inclusive of the "view source" file).

Today is: @DateTime.Now

And the following will be output onto the page, seemingly looking just like the rest of the HTML plain text on it:

Today is: 7/8/2014 4:56:04 PM

You can see how it combines HTML div tags with some .NET properties (DateTime.Now). Razor uses pieces of both to simplify tasks and shoot an output to the browser for users. The syntax can vary sometimes from both, but tends to be shorter and simpler. Overall, the goal is to render HTML and make life easier for the web developer.

In Razor, the expression begins right after the @ symbol and ends at the closing bracket.

As a sample:
If/else statement using Web Forms syntax:

<% if(User.IsAuthenticated) { %>
    Hello, <%: User.Username %>!
<% } %>
<% else { %>
    Please <%: Html.ActionLink("Login") %>
<% } %>

Razor syntax:

@if(User.IsAuthenticated) {
    Hello, @User.Username!
} else {
    Please @Html.ActionLink("Login")

Though they use a different syntax, both render the same HTML to the browser!

Source: WPF 4.5 Unleashed