Dissecting Razor, part 6: Function Blocks

After looking at how Razor’s Execute() method is generated, we will turn to class-level features.

C# Razor pages can define class members inside of @functions { ... } blocks.  These are Razor’s equivalent of <script runat="server"> blocks in ASPX pages.  VBHTML pages use @Functions ... End Functions instead.

Functions blocks are emitted directly into top of the generated class, regardless of their location in the original source.  Unlike code blocks, function blocks cannot contain markup.

Here is a simple example:

<!DOCTYPE html>
<html>
    <body>
        @functions{
            public int GetPageLength() {
                //Don't try this in production.
                return ((StringWriter)this.Output).ToString().Length;
            }
        }
        @GetPageLength() characters have been written so far.
    </body>
</html>
@{ #error } 

Note that functions blocks can be defined anywhere, even in the middle of the markup.  The location of the block is totally irrelevant.

Here is the generated C# source, with a comment indicating where the block used to be.

public class _Page_Razor_Functions_cshtml : System.Web.WebPages.WebPage {

#line hidden
#line 4 "...\Functions.cshtml"

    public int GetPageLength() {
        //Don't try this in production.
        return ((StringWriter)this.Output).ToString().Length;
    }

#line default
#line hidden

    public _Page_Razor_Functions_cshtml() {
    }

    protected ASP.global_asax ApplicationInstance {
        get {
            return ((ASP.global_asax)(Context.ApplicationInstance));
        }
    }

    public override void Execute() {
        WriteLiteral("<!DOCTYPE html>\r\n<html>\r\n    <body>\r\n        ");
//Here was the functions block
        WriteLiteral("\r\n        ");

#line 10 "...\Functions.cshtml"
        Write(GetPageLength());
#line default
#line hidden
        WriteLiteral(" characters have been written so far.\r\n    </body>\r\n</html>\r\n");

#line 13 "...\Functions.cshtml"
#error

#line default
#line hidden
        WriteLiteral("     ");
    }
}

The contents of the functions block is inserted at the very top of the class, with the familiar #line directives to pretend that it comes from the CSHTML.

Notice that none of the whitespace around the functions block is stripped; you can see the newline and indentation in the @functions line in the first WriteLiteral string, and the newline and indentation after the closing } in the second WriteLiteral string.

Sure enough, the rendered HTML contains an extra blank like:

<!DOCTYPE html>
<html>
    <body>
        
        55 characters have been written so far.
    </body>
</html>

This means that putting a functions block before the <!DOCTYPE> will cause the HTML to start with an ugly blank line.  Therefore, it’s best to put functions blocks at the end of the source, where the blank lines won’t matter.

Next Time: Helpers

12 comments:

Great tutorial. Thanks a lot

see page

I advise you to check https://domyhomework.guru/blog/make-homework-fun out if you want to make homework fun. It will help you to achieve success

We will discuss a great programming language as you know, the Razor syntax is based on the C# programming language, and that's the language that's used most often with ASP.NET Web pages. However, the Razor syntax also supports the Visual Basic language, and everything you see you can also do in Visual Basic. This is very helpful programming language for developers. Coursework writing services.

mr jatt Mp3 New Punjabi Song,Single Tracks Latest song download also Listen Latest Music Albums Online in High Quality at Mrpendus.in
mr jatt

I really like the contents of your site, this is very meaningful for me. Thanks for sharing an amazing post.
amino pc

Knowing all ins and outs of how to write A-grade papers, our academic paper writers are willing to share edusson review this knowledge with you and help become a more successful student.

Another advantage of writing a term paper by ordering it from writers from essay help is that you are guaranteed to get a high score. Even if you are a very diligent student who closely studies all disciplines, it is far from the fact that you will write your term paper well. And if you are not completely sure of your abilities, then it is much better to play it safe and order a term paper

Objects are commonly used in server coding. The "DateTime" object is a typical built-in ASP.NET object, but other types of objects, such as web pages, text boxes, files, database records, etc., can also be self-defined. Objects could be capable of performing methods. There may be a "Save" method for a database record, a "Rotate" method for an image object, a "Send" method for an email object, and so on. Additionally, objects contain attributes that define them. FirstName and LastName properties may be present in a database record (among others). The Now property of the ASP.NET DateTime object (written as DateTime.Now) contains a Day property (written as DateTime.Now.Day). You can download this app or more in our site.

Adam,
https://playpc.io/editorial/in-game-ads-players-starting-to-warm-up-on-the-issue/

I really like the contents of your site, this is very meaningful for me.
film plus apk

I really want to appreciate you for this type of article. It is a nice informative content. Now its time to avail limo service east bay ca for more information.

Discover how Function Blocks enable you to modularize your code, promote code reuse, and foster a more efficient development process. We'll cover topics such as parameterization, scoping, and invoking Function Blocks within Razor views, equipping you with the knowledge and tools to harness the full power of this feature.
violation of a protective order virginia

Post a Comment