The Difference Between @Helpers and @Functions In WebMatrix
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的更多相关文章
- (转)MVC语法-@helpers和@functions(Razor内定义函数)
(转)MVC语法-@helpers和@functions(Razor内定义函数) 转自:http://www.mikesdotnetting.com/Article/173/The-Differenc ...
- 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 ...
- 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 ...
- 编译rnnlib
rnnlib,一个多年不更新的rnn库,编译的过程有点麻烦,好多东西要选特定版本的.这里记录一下我的配置脚本,在ubuntu14.04下测试ok. P.S fedora下好像不能直接用包管理来安装指定 ...
- 【转】Basic C# OOP Concept
This Article will explain a very simple way to understand the basic C# OOP Concept Download ShanuBas ...
- HeapAlloc、GlobalAlloc和new等内存分配有什么区别么?
查找了一些 new , GlobalAlloc, HeapAlloc分配内存方式的区别. 转了一些资料 //============================================== ...
- malloc()与calloc差别
Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slig ...
- directive(指令里的)的compile,pre-link,post-link,link,transclude
The nitty-gritty of compile and link functions inside AngularJS directives The nitty-gritty of comp ...
- 理解用requireJs 来实现javascript的模块化加载
这是我看到的一片关于requirejs的初学者的文章,写的不错,下面结合自己的理解记录一下: 原文:http://www.sitepoint.com/understanding-requirejs-f ...
随机推荐
- 【转】简单明了区分escape、encodeURI和encodeURIComponent
一.前言 讲这3个方法区别的文章太多了,但是大部分写的都很绕.本文试图从实践角度去讲这3个方法. 二.escape和它们不是同一类 简单来说,escape是对字符串(string)进行编码(而另外两种 ...
- bzoj 1597 [Usaco2008 Mar]土地购买——斜率优化dp
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1597 又一道斜率优化dp.负数让我混乱.不过仔细想想还是好的. 还可以方便地把那个负号放到x ...
- centos7防火墙 启动和关闭
CentOS 7.0默认使用的是firewall作为防火墙,这里改为iptables防火墙.firewall:systemctl start firewalld.service #启动firewa ...
- 密码生成工具Cupp
Cupp可根据已知信息生成相应的字典,用来爆破很有帮助 首先先安装一下cupp 命令:apt-get install cupp 参数说明: -v查看cupp版本号 -h 查看参数列表 -l 从gith ...
- java - 只输出中文, 包含中文标点符号
在 Java 中直接使用Unicode 转码时会按照UTF-16LE 的方式拆分,并加上 BOM. 如果采用 UTF-16 拆分,在 Java 中默认采用带有 BOM 的 UTF-16BE 拆分. S ...
- Lambda表达式中使用正则表达式
某语句如果不用正则表达式: string[] names = { "Tom", "Dick", "Harry", "Mary&qu ...
- html5调用本机摄像头兼容谷歌浏览器高版本,谷歌浏览器低版本,火狐浏览器
做这个功能的时候在网上查了一些资料,代码如下,在这个代码在谷歌浏览器46版本是没问题的,在火狐浏览器也行,但是在谷歌浏览器高版本下是不兼容的 <div id="body"&g ...
- 上传图片用图片文件的对象hash哈希值判断图片是否一样,避免重复提交相同的图片到服务器中
上传图片用图片文件的对象hash哈希值判断图片是否一样,避免重复提交相同的图片到服务器中 前端:要用到一个插件,点击下载 <!DOCTYPE html> <html xmlns=&q ...
- 【原】Coursera—Andrew Ng机器学习—课程笔记 Lecture 4_Linear Regression with Multiple Variables 多变量线性回归
Lecture 4 Linear Regression with Multiple Variables 多变量线性回归 4.1 多维特征 Multiple Features4.2 多变量梯度下降 Gr ...
- JanusGraph : 图和图数据库的简介
JanusGraph:图数据库系统简介 图(graph)是<数据结构>课中第一次接触到的一个概念,它是一种用来描述现实世界中个体和个体之间网络关系的数据结构. 为了在计算机中存储图,< ...