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

Sunday, March 20, 2011 9:42 AM

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

Both @helpers and @functions do share one thing in 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 is what might cause a bit of confusion about their roles. However, they are not the same. In essence, a helper is a reusable snippet of Razor sytnax exposed as a method, and is intended for rendering HTML to the browser, whereas a function is static utility method that can be called from anywhere within your Web Pages application. The return type for a helper is always HelperResult, whereas the return type for a function is whatever you want it to be.

A typical example of a helper is to display items in an ordered list. You create a folder called App_Code in the root of your site, if you don't have one already, and add a .cshtml file to it. You can name this file anything you 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 item in 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 an ordered list within a Web Page. When the code is compiled, OrderedList becomes a static method of non-static class called Helpers - the name of the class is taken from the file name. A sample method call could look like this:

@Helpers.OrderedList(new[] { "Blue", "Red", "Green" })

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

@using System.Web.Mvc;
@using System.Text;
@functions { public static HtmlString OrderedList(IEnumerable<string> items)
{
var sb = new StringBuilder();
var orderedList = new TagBuilder("ol");
foreach(var item in items){
var listItem = new TagBuilder("li");
listItem.SetInnerText(item);
sb.AppendLine(listItem.ToString(TagRenderMode.Normal));
}
orderedList.InnerHtml = sb.ToString();
return new HtmlString(orderedList.ToString(TagRenderMode.Normal));
}
}

Again, OrderedList becomes a method of a non-static class named after the file (Functions), and calling it in 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 you could have rendered the HTML tags as strings yourself), and make sure you returned an object of type HtmlString to ensure that the whole lot doesn't get HTML encoded when it is rendered to the ouput. Functions cannot contain intermixed HTML. Now you can see the attraction of @helpers.

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

@functions {
public static bool IsBeforeToday(string value){
DateTime result;
if (DateTime.TryParse(value.ToString(), out result))
{
if (result < DateTime.Now)
{
return true;
}
}
return false;
}
}

This function takes a string as an input, and tests to see if it can be converted to a DateTime successfully. If so, it tests to see if it is 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 that the return type for both @functions examples have differed - the first is an HtmlString, whereas the second is a bool. The return type for a method compiled from @helpers will always be HelperResult.

One other thing to note - I've emphasised that the class that is compiled as a result of the @functions syntax is non-static. This means that you cannot create extensions methods using @functions.

The Difference Between @Helpers and @Functions In WebMatrix的更多相关文章

  1. (转)MVC语法-@helpers和@functions(Razor内定义函数)

    (转)MVC语法-@helpers和@functions(Razor内定义函数) 转自:http://www.mikesdotnetting.com/Article/173/The-Differenc ...

  2. Creating Your Own PHP Helper Functions In Laravel

    By Hamza Ali LAST UPDATED AUG 26, 2018  12,669 104 Laravel provides us with many built-in helper fun ...

  3. Practical Go: Real world advice for writing maintainable Go programs

    转自:https://dave.cheney.net/practical-go/presentations/qcon-china.html?from=timeline   1. Guiding pri ...

  4. 编译rnnlib

    rnnlib,一个多年不更新的rnn库,编译的过程有点麻烦,好多东西要选特定版本的.这里记录一下我的配置脚本,在ubuntu14.04下测试ok. P.S fedora下好像不能直接用包管理来安装指定 ...

  5. 【转】Basic C# OOP Concept

    This Article will explain a very simple way to understand the basic C# OOP Concept Download ShanuBas ...

  6. HeapAlloc、GlobalAlloc和new等内存分配有什么区别么?

    查找了一些 new , GlobalAlloc, HeapAlloc分配内存方式的区别. 转了一些资料 //============================================== ...

  7. malloc()与calloc差别

    Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slig ...

  8. directive(指令里的)的compile,pre-link,post-link,link,transclude

    The nitty-gritty of compile and link functions inside AngularJS directives  The nitty-gritty of comp ...

  9. 理解用requireJs 来实现javascript的模块化加载

    这是我看到的一片关于requirejs的初学者的文章,写的不错,下面结合自己的理解记录一下: 原文:http://www.sitepoint.com/understanding-requirejs-f ...

随机推荐

  1. 讲解JSP自定义标签

    一.基本概念 1.标签(Tag) 标签是一种XML元素,通过标签可以使JSP网页变得简洁并且易于维护,还可以方便地实现同一个JSP文件支持多种语言版本.由于标签是XML元素,所以它的名称和属性都是大小 ...

  2. 十大Java人物

    James Gosling : Java之父文/陶文 作 为Java之父,James Gosling的名字可谓是耳熟能详.当人们评论一种编程语言时,总喜欢捎带着把下蛋的母鸡一起带上.Java做为中国的 ...

  3. (转)Android高性能编程(2)--延迟初始化

    上一篇文章,讲到了很多Android应用开发中需要注意的性能和内存方面的技巧.这一篇文章就是从smali指令级来分析性能优化和内存优化的问题. 如何解决界面启动时间开销大的问题 我们在编写Androi ...

  4. 关于Android Studio上得处女座福音功能——reformat code

    在mac上,选中需要的代码,然后 Option+(shift) + Command + L 全部重新排列!!爽飞!

  5. AzureStack混合云大数据解决方案

    AzureStack是Azure的私有云解决方案.AzureStack可以帮助用户实现混合云的部署模式. 本文将介绍混合云的模式下,Azure作为计算资源,AzureStack作为存储资源.如下图: ...

  6. ATM:模拟实现一个ATM + 购物商城程序

    额度 15000或自定义 实现购物商城,买东西加入 购物车,调用信用卡接口结账 可以提现,手续费5% 支持多账户登录 支持账户间转账 记录每月日常消费流水 提供还款接口 ATM记录操作日志 提供管理接 ...

  7. mysql索引设计

    mysql索引设计 1.B树与B+树的区别?B-Tree:一个节点可以拥有大于2个子节点的平衡多叉树,所有关键字在整颗树中出现,包括在非叶子节点也能命中, 叶子节点之间没有链表B+Tree:每个叶子节 ...

  8. python开发模块基础:collections模块&paramiko模块

    一,collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdic ...

  9. apk、图片下载工具(1)

    package com.js.ai.modules.pointwall.util; import java.io.BufferedInputStream; import java.io.Buffere ...

  10. Android:通过滤镜实现点击图片变暗效果

    实现点击图片(ImageView)变暗效果,有一个较简单的方法,就是讲目标图片设置为背景图片(setBackground),再创建一个selector.xml文件,里面放置一张普通状态时的透明图片,一 ...