(转)MVC语法[email protected]和@functions(Razor内定义函数)

(转)MVC语法[email protected]和@functions(Razor内定义函数)

转自:http://www.mikesdotnetting.com/Article/173/[email protected]@Functions-In-WebMatrix

The Difference Between @Helpers and @Functions In WebMatrix

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.

时间: 2024-10-04 22:21:10

(转)MVC语法[email protected]和@functions(Razor内定义函数)的相关文章

3.MVC框架开发(Razor内嵌函数)

1.建立没有返回值的Razor内嵌函数(但是能直接输出内容) 必须以@符号开头,没有返回值但能直接输出内容,比如: @helper showTitle(string strTitle){ if(strTitle.Length > 8){ @(strTitle.Substring(0,8)+"...") //输出内容 }else{ @strTitle //输出内容 } } 2.建立有返回值的Razor内嵌函数 必须以@functions开头且里面是一个静态方法,比如通过图书ISBN

Razor 中定义函数

//声明函数 @helper GetWeek(int week) { switch (week) { case 0: @:星期天 break; case 1: @:星期一 break; case 2: @:星期二 break; case 3: @:星期三 break; case 4: @:星期四 break; case 5: @:星期五 break; case 6: @:星期六 break; default: @:星期天 break; } } //调用函数 <label for="radi

C99语法之可变参宏和内联函数

可变参宏: 1 #include<stdio.h> 2 #include<stdlib.h> 3 4 #define MYPRINT(...) printf(__VA_ARGS__) 5 6 int main(int argc, char **argv) 7 { 8 MYPRINT("%d,%s", 10, "hello china"); 9 getchar(); 10 return 0; 11 } 使用 ... 来指明多参,使用宏 __A_

Bash 4.4 中新增的 ${[email&#160;protected]} 语法

Bash 4.4 中新增了一种 ${...} 语法,长这样:${[email protected]}.根据不同的 operator,它展开后的值可能是 parameter 这个参数的值经过某种转换后的值,又可能是关于 parameter 参数自身的某种信息.这句话太抽象了,还是看下面的详细解释吧. operator 一共有 5 种值,分别是 Q.E.P.A.a,都是单个的字母. Q quote 的缩写,这个 operator 的功能是把 parameter 的值加上合适的引号,从而转换成在脚本中

[email&#160;protected] 深入学习之——初探spring mvc

一.简介 Spring MVC是Spring框架的最重要的模块之一,它构建于Spring IoC容器之上,大量使用容器的特性简化其配置.MVC模式消除了业务逻辑与UI的耦合.模式负责封装视图展示的应用数据:视图只显示数据,不包含任何业务逻辑:控制器负责接收用户请求并调用后端服务进行业务处理,处理之后,后端服务可能返回某些数据供视图显示.其核心思想是分离业务逻辑与UI,使系统能够独立修改,互不影响. Spring MVC应用,模式通常由服务层处理和持续层存储的领域对象组成.视图通常是用Java标准

[email&#160;protected]初体验之前篇-回顾[email&#160;protected]创建项目的流程

模拟实际工作中的操作,假如新开启了一个vue项目,可以先看看上篇博文中的git操作,新建空仓库vue-demo,并拉取到本地,创建本地dev分支后 1. 全局安装vue-cli yarn global add vue-cli // 检查是否已安装成功 vue -V // 2.9.6 2. 使用vue init 创建项目,官方提供了6种模板,对于大多数人而言,工作中选择webpack模板 // 使用vue init 创建项目(.指当前目录) vue init webpack . ? Generat

[email&#160;protected]动态代理-类加载器

一.测试单元     概述:用于测试JAVA代码的工具类,已内置在Eclipse中;     格式:         1.在方法的上面添加@Test;         2.对被测试的方法的要求:权限-public;返回值-void;参数-空参         [email protected]:在@Test标注的方法前执行,可以用于初始化;           @After:在@Test标注的方法后执行,可以用于释放资源; 二.注解     概述:java的一种数据类型,和类/接口在同一级别  

15-02-28-协议[email&#160;protected] 接口

// //  main.m //  05-protoco // //  Created by apple on 13-8-11. //  Copyright (c) 2013年 itcast. All rights reserved. // /* 1.协议的定义 @protocol 协议名称 <NSObject> // 方法声明列表.... @end 2.如何遵守协议 1> 类遵守协议 @interface 类名 : 父类名 <协议名称1, 协议名称2> @end 2>

[email&#160;protected]的心得

今天练习了一下@ResponseBody,主要是对json字符返回有了新的了解. 1.配置@ResponseBody: 在Spring-Servlet.xml中开启注解配置: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.