The difference between @Helpers and @Functions in WebMatrix

Source: Internet
Author: User

From:http://www.mikesdotnetting.com/article/173/the-difference-between-helpers-and-functions-in-webmatrix

Sunday, March, 9:42 AM

This is another post which were inspired by a recent question in the net forums when someone asked what the difference is between @functions and @helpers in ASP. Web Pages. Here, I look at both of these contructs and explain what they is, how they is different, and how each should is used app Ropriately.

Both @helpers and @functions do share one thing on Common-they make code reuse a possibility within Web Pages. They also share another thing in Common-they look the same at first glance, which are what might cause a bit of confusion about their roles. However, they is not the same. In essence, a helper is a reusable snippet of Razor Sytnax exposed as a method, and are intended for rendering HTML to the browser, whereas a function is static utility method The can be called from anywhere within your WEB Pages application. The return type for a helper was always helperresult, whereas the return type of a function is whatever you want it to be.

A typical example of a helper is to display the items in an ordered list. You create a folder called App_Code with the root of your site, if you don't have one already, and add a . cshtml fi Le to it. You can name this file anything your like-but Helpers seems to be appropriate. Within your helpers.cshtml file, you would add the following code:

@helper orderedlist (ienumerable<string> items) {    <ol>        @foreach ( var inch items) {            <li> @item </li>        }    </ol>}

As you can see, this code includes HTML tags and Razor code, just like it would if you were rendering a ordered list with In a Web Page. When the code is compiled, orderedlist becomes a static method of Non-static class called helpers-the name of the CL The taken from the file name. A Sample method call could:

@Helpers. Orderedlist (new"Blue""Red" " Green " })

When this was executed, unencoded HTML is output to the browser. You could implement the same functionality using @functions, and here are an example which does just. Again, need to add a . cshtml file to App_Code, and give it a name. In the case. functions.cshtml is as good as any:

@using SYSTEM.WEB.MVC; @using System.Text; @functions { Public StaticHtmlstring Orderedlist (ienumerable<string>items) {        varSB =NewStringBuilder (); varOrderedlist =NewTagbuilder ("ol"); foreach(varIteminchitems) {            varListItem =NewTagbuilder ("Li");            Listitem.setinnertext (item); Sb.        Appendline (listitem.tostring (tagrendermode.normal)); } orderedlist.innerhtml=sb.        ToString (); return Newhtmlstring (orderedlist.tostring (tagrendermode.normal)); }}

Again, Orderedlist becomes a method of a non-static class named after the file (Functions), and calling it on the page is Straightforward:

@Functions. Orderedlist (new"Blue""Red" " Green " })

But Oh lordy! You ' ve had to reference System.Text to create a StringBuilder object and SYSTEM.WEB.MVC to use the Tagbuilder (although Yo U could has rendered the HTML tags as strings yourself), and make sure you returned a object of type htmlstring to Ensure that the whole lot doesn ' t get HTML encoded when it's rendered to the ouput. Functions cannot contain intermixed HTML. Now you can see the attraction of @helpers.

The appropriate use for @functions are when you want to perform an operation on a variable, rather than output some HTML . For example, might want to validate a incoming datetime to ensure that it's some time I n the past. You wouldn ' t accept a form submission where someone's date of birth is some time on the future? This is where @functions can used:

@functions {        publicstaticbool isbeforetoday (string  value) {      DateTime result;       if  out result))      {        if (Result < DateTime.Now)        {          returntrue ;        }      }       return false ;    }}

This function is takes a, string as an input, and tests to the if it can be converted to a DateTime successfully. If so, it tests to see if it's before the current date and time. If It passes those tests, it returns true:

@Functions. Isbeforetoday ("2010/3/22") @*returns true*@ @Functions. Isbeforetoday (  "2012/5/6") @*returns False at the time of writing*@

Notice the return type for both @functions examples has differed-the first is an htmlstring, whereas the Secon D is a bool. The return type for a method compiled from @helpers would always be helperresult.

One other thing to Note-i ' ve emphasised, the class that's compiled as a result of the @functions syntax is Non-stat IC. This means cannot create extensions methods using @functions.

The difference between @Helpers and @Functions in WebMatrix

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.