Friday, May 13, 2011

ASP.NET MVC 3 supports a new view-engine option called “Razor” (in addition to continuing to support/enhance the existing .aspx view engine).  Razor minimizes the number of characters and keystrokes required when writing a view template, and enables a fast, fluid coding workflow.

Unlike most template syntaxes, with Razor you do not need to interrupt your coding to explicitly denote the start and end of server blocks within your HTML. The Razor parser is smart enough to infer this from your code. This enables a compact and expressive syntax which is clean, fast and fun to type.

You can learn more about Razor from some of the blog posts I’ve done about it over the last last 9 months:

Today’s blog post covers a cool feature of Razor that a lot of people don’t know about – which is the ability to define re-usable helper methods using the @helper syntax.

Simple @helper method scenario

The @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates.  They enable better code reuse, and can also facilitate more readable code.  Let’s look at a super-simple scenario of how the @helper syntax can be used.

Code before we define a @helper method

Let’s look at a simple product listing scenario where we list product details, and output either the price of the product – or the word “FREE!” if the item doesn’t cost anything:

The above code is fairly straight-forward, and Razor’s syntax makes it easy to integrate server-side C# code within the HTML.

One place that is a little messy, though, is the if/else logic for the price.  We will likely output prices elsewhere within the site (or within the same page), and duplicating the above logic everywhere would be error-prone and hard to maintain.  Scenarios like this are prime candidates to extract and refactor into helper methods using the @helper syntax.

Refactoring the above sample using the @helper syntax

Let’s extract the price output logic, and encapsulate it within a helper method that we’ll name “DisplayPrice”.  We can do this by re-writing the sample to the code below:

We’ve used the @helper syntax above to define a reusable helper method named “DisplayPrice”.  Just like a standard C#/VB method, it can contain any number of arguments (you can also define the arguments to be either nullable or optional).  Unlike standard C#/VB methods, though, @helper methods can contain both content and code, and support the full Razor syntax within them – which makes it really easy to define and encapsulate rendering/formatting helper methods:

You can invoke @helper methods just like you would a standard C# or VB method:

Visual Studio will provide code intellisense when invoking the method:

Reusing @helpers across multiple views

In the example above, we defined our @helper method within the same view template as the code that called it.  Alternatively, we can define the @helper method outside of our view template, and enable it to be re-used across all of the view templates in our project.

We can accomplish this by saving our @helper methods within .cshtml/.vbhtml files that are placed within a\App_Code directory that you create at the root of a project.  For example, below I created a “ScottGu.cshtml” file within the \App_Code folder, and defined two separate helper methods within the file (you can have any number of helper methods within each file):

Once our helpers are defined at the app level, we can use them within any view template of our application.

The ScottGu.cshtml template in the \App_Code folder above will logically compile down to a class called “ScottGu” with static members of “DisplayPrice” and “AnotherHelper” within it.  We can re-write our previous sample to call it using the code below:

Visual Studio will provide code intellisense when calling app-level helpers like this:

May 15th Update: One issue that a few people have pointed out is that when a @helper is saved within the \app_code directory, you don’t by default get access to the ASP.NET MVC Html helper methods within it (e.g. Html.ActionLink(), Html.TextBox(), etc).  You do get access to the built-in HTML helper methods when they are defined in the same file as your views.  This is not supported out of the box, though, when the helpers are within the \app_code directory - we’ll add this in the next release.  Paul Stovall has a nice helper class that you can use in the meantime to access and use the built-in Html helper methods within @helper methods you define in the \app_code directory.  You can learn how to use it here.

Summary

Razor’s @helper syntax provides a convenient way to encapsulate rendering functionality into helper methods that you can re-use within individual view templates, or across all view templates within a project.

You can use this functionality to write code that is even cleaner and more maintainable.

Hope this helps,

Scott

ASP.NET MVC 3 and the @helper syntax within Razor的更多相关文章

  1. 返璞归真 asp.net mvc (9) - asp.net mvc 3.0 新特性之 View(Razor)

    原文:返璞归真 asp.net mvc (9) - asp.net mvc 3.0 新特性之 View(Razor) [索引页][源码下载] 返璞归真 asp.net mvc (9) - asp.ne ...

  2. [asp.net mvc 奇淫巧技] 02 - 巧用Razor引擎在Action内生成Html代码

    在web开发中经常会遇到在内部代码中获取Html,这些Html是需要和数据进行一起渲染.并不是直接把Html代码返回给客户端.这样的做法有很多应用场景,例如分页.Ajax一次性获取几段Html片段.生 ...

  3. ASP.NET MVC 第八回 Helper之演化

    题目:如何在View中写一个超级连接连接到主页? 这个问题看起来很好回答: <a href="/home/index">首页</a> 其实上面这种不能称之为 ...

  4. asp.net mvc页面javascript代码中如何使用razor

    我们需要用<text>将javascript代码包含起来,强制让razor编译器回到内容模式, 或者将javascript代码放在函数中,让razor编译器可以识别,请看下面两个例子: & ...

  5. ASP.NET MVC 3和Razor中的@helper 语法

    原文:http://kb.cnblogs.com/page/102191/ ASP.NET MVC 3支持一项名为"Razor"的新视图引擎选项(除了继续支持/加强现有的.aspx ...

  6. (转)ASP.NET MVC 3和Razor中的@helper 语法

    转自:http://kb.cnblogs.com/page/102191/ ASP.NET MVC 3支持一项名为“Razor”的新视图引擎选项(除了继续支持/加强现有的.aspx视图引擎外).当编写 ...

  7. ASP.NET MVC 3和Razor中的@helper

    ASP.NET MVC 3支持一项名为“Razor”的新视图引擎选项(除了继续支持/加强现有的.aspx视图引擎外).当编写一个视图模板时,Razor将所需的字符和击键数减少到最小,并保证一个快速.通 ...

  8. ASP.NET MVC HtmlHelper用法集锦

    ASP.NET MVC HtmlHelper用法集锦 在写一个编辑数据的页面时,我们通常会写如下代码 1:<inputtype="text"value='<%=View ...

  9. [转]ASP.NET MVC 入门11、使用AJAX

    在ASP.NET MVC beta发布之前,M$就宣布支持开源的JS框架jQuery,然后ASP.NET MVC beta发布后,你建立一个ASP.NET MVC beta的项目后,你可以在项目的sc ...

随机推荐

  1. vue 相邻自定义组件渲染错误正确的打开方式

    话不多说看问题: 当封装自定义组件时例如(自定义下拉列表)两个相同的组件在多次v-if变化时偶尔会发生渲染错误,明明赋值正确但是组建中的ajax方法可能返回的数据乱掉,或者其他神逻辑错误. 经过查询发 ...

  2. 半导体巨头青睐物联网领域 众强联手打造MCU生态系统

    随着万物互联的时代到来,众多半导体巨头纷纷转战物联网领域.早在十年前,意法半导体曾将STM32推向市场,意法半导体对32位MCU在物联网方面的应用在两年前就已展开攻势. 4月25日,历经两届盛况的ST ...

  3. Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

    python3.6.3  我在处理爬虫时候使用BeautifulSoup中遇到报错 “ bs4.FeatureNotFound: Couldn't find a tree builder with t ...

  4. java.输入水果的编号,求它对应的单价

    总结:可以if-else 循环或switch循环 package com.b; import java.util.Scanner; /*以下4种水果的单价分别是3.00元/公斤,2.50元/公斤,4. ...

  5. thinkphp中的_initialize方法

    子类的_initialize方法自动调用父类的_initialize方法.而php的构造函数construct,如果要调用父类的方法,必须在子类构造函数显示调用parent::__construct( ...

  6. ARM-Linux移植之(三)——init进程启动流程分析

    我们通常使用Busybox来构建根文件系统的必要的应用程序.Busybox通过传入的参数来决定执行何种操作.当init进程启动时,实际上调用的是Busybox的init_main()函数,下面我们来分 ...

  7. ARM-Linux内核移植之(一)——内核启动流程分析

    内核版本:2.6.22  为什么要采用这样一个较低的版本进行移植了,因为韦东山大牛说了,低版本的才能学到东西,越是高版本需要移植时做的工作量越少,学的东西越少. 内核启动分为三个阶段,第一是运行hea ...

  8. maven(基础介绍一)

    maven:提供的作用有以下几点: 1 jar包依赖 这个也许会maven最突出的特点了使用maven不需要上网单独下载jar包,只需要在配置文件pom.xml中配置jar包的依赖关系,就可以自动的下 ...

  9. docker image 转换 docker file

    这个是从每天的播报平台抓取到国外的信息发现的,感觉很实用. 博客原文,E文好的可以直接去看,https://samaritan.ai/blog/reversing-docker-images-into ...

  10. in not in 和 null , in 判断范围中可以包含null,而not in判断不能包括null

    oracle中,任何字符串与null比较得到的结果都是null,而 oracle的判断条件为null时就退出判断(?) 因此判断某个字符串是否在一个集合中时,not in 和 in的结果完全不一样,如 ...