下面就和大家分享下我在asp.net官网看到的资料,学习到的点语法。
1.通过使用@符号,可以直接在html页面中写C#或者VB代码:

运行后:

2.页面中的C#或者VB代码都放在大括号中。

运行后:

3.每一行代码通过分号来结束:

运行后:

4.在页面中输出特殊字符,双引号和斜杠:

运行效果:

5.通过Request属性得到当前页面的url,RequestType等。

运行结果:

6.通过if---else:
场景是,我们通过判断当前浏览器是否向服务器端post数据,如果post则提示你点击了Post按钮。

运行后:

- 爱因斯坦小脑 2011-05-02 14:55
成都创新互联主要从事网站制作、
成都网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务同心,十多年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575
下面是一个完整的例子:

当点击submit按钮后,@totalMessage将会是输入text1和text2的和。

Razor中还有自己的类型转化:

另外就是Razor中的注释,有两种方式-:

- 爱因斯坦小脑 2011-05-02 15:04
和Webform引擎相似,Razor语法也允许让一些服务器端的代码嵌入到web页面。客户端的代码主要是一些html和css,javascript等。当页面中有服务器端需要解析的代码时,这些Razor语法的代码会动态的被编译成HTML标记,并返回到客户端。
Web form引擎的文件必须是aspx或者ascx后缀的,Razor的文件时cshtml或者是vbhtml后缀。服务器端是通过文件后缀来决定当前的文件是否使用了Razor语法。
Razor也是在Asp.net基础上的一种新的语言,它和asp.net以及.net framework平台的关系如下:

所以如果你的网站现在使用的是Asp.net那么你就可以现在开始不适用.aspx和ascx页面而使用.cshtml或者vbhtml页面,我只知道在asp.net mvc中只要把对应的试图引擎给注册下酒行了。 对于传统的asp.net网站就不大了解如何同时使用几个试图引擎了。
1.更加简洁的让text,html和代码集合到一起
例子:

上面是使用Razor引擎的代码,如果使用webform试图引擎,你需要使用<% %>标记来把代码和html集合到一起,但从把代码和html集合到一起来看,@符合也就是比<%%>少写一个标记,但是如果代码行数多了以及对于if else的判断使用的花括号都需要<%%>标记,你就会感觉的Razor真的是简洁了不少。
运行效果:

2.@: 的使用和
标记的使用:
@: 用来输出文本或者是那些未能找到匹配的Html标记的标记符。如果是单行使用@:,但是对于多行代码显示,就可以使用text标签来替代@:了。
例子:

这个我运行的结果好像和预期的不一样。。。。
使用标记也是一样的效果,难道是RTM版本把这个功能去掉了??、???
3.变量赋值时换行的问题。

你可以一行内为变量赋值,或者是在其它行开始时为变量赋值,或者是使用转义符号@,上面例子的1,2,3种情况是正确的赋值,但是方括号包住的会直接报错。
4.变量的类型:

Razor中的数据类型和C#中的差不多,很多C#的变量类型以及声明变量的方式,都可以在Razor中看到。。。。。比如上面的stirng name=”Joe”; int count=5;等。
- 爱因斯坦小脑 2011-05-02 15:06
Raozr中文件目录的获取:
和webform引擎相似,例子:

运行效果:

5.条件判断和循环的使用
条件判断有if, switch等,
先看使用if条件判断的例子:

如果是在C#中,上面的if(showToday)后面不需要是用大括号也可以正常显示,但是在Razor中,如果不加这个大括号,你就杯具了。
使用if…else的例子:

上面的例子中我们使用了if---else,这个和C#中的相同,如果你仔细看发现下面有个@:或者是我注释掉的标记,它们的作用是在Razor代码中能够输出文本。而不需要输出html。
switch条件判断例子:

运行结果:

循环就不用说了for,foreach,以及while。
for循环:


foreach的使用:

- 爱因斯坦小脑 2011-05-02 15:08
6.超链接的使用。
在Razor中有个方法是Href,它主要是用来在img标签和link以及a标签中得到对应的文件的完全url而设计的。
例如:

运行:
除了这些语法,在Razor中也可以使用System.Generic.Collection中的那些容器。比如Dictionary.
也支持直接在Razor代码中捕获异常。
当前文章:Razor视图引擎语法学习(二)-创新互联
文章URL:http://mswzjz.cn/article/dhhscp.html