ASP.NET Razor
一、Razor简介:
1、Razor不是编程语言,它是服务器端标记语言,是一种允许您向网页中嵌入基于服务器的代码(vb,c#)的标记语法;
2、当网页被写入浏览器时,基于服务器的代码能够创建动态内容。在网页加载时,服务器在向浏览器返回页面之前,会执行页面内的基于服务器代码。由于是在服务器上运行,这种代码能执行复杂的任务,比如访问数据 库。
3、Razor基于ASP.NET,它为web应用程序的创建而设计。它拥有传统ASP.NET标记的能力;
4、Razor帮助器可通过简单的Razor代码进行访问(您可以使用 Razor 语法构建自己的帮助器,或者使用内建的 ASP.NET 帮助器);
5、Razor同时支持C#和VB;
二、Razor(c#)语法:
1、Razor代码封装于@{......}中;
2、行内表达式(变量和函数)以@开头;
3、代码语句以分号结尾;
4、字符串由引号包围;
5、c#代码对大小写敏感;
6、c#文件的扩展名是.cshtml;
7、实例:
单行代码块:@{var myMessage="hello world !"}
行内表达式或变量:<p>The Value of Messsage is : @myMessage </p>
多行语句代码块:@{var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Here in Huston it is: " + weekDay;
}
<p>The greeting is: @greetingMessage</p>
三、C#循环:
1、For循环:
<html>
<body>
@for(var i=10,i<21,i++)
{
<p>Line @i</p>
}
</body>
</html>
2、Foreach循环:
如果您需要处理集合或数组,则通常要用到Foreach循环
<html>
<body>
<ul>
Foreach(var ite in Request.ServerVariables)
{
<li>@ite</li>
}
</ul>
</body>
</html>
3、While循环:
<html>
<body>
@{
var i = 0;
while (i < 5)
{
i += 1;
<p>Line #@i</p>
}
}
</body>
</html>
四、C#逻辑:
1、if条件:
@{var price=50;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
</body>
</html>
2、Else条件:
@{var price=20;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
3、else if条件:
@{var price=25;}
<html>
<body>
@if (price>=30)
{
<p>The price is high.</p>
}
else if (price>20 && price<30)
{
<p>The price is OK.</p>
}
else
{
<p>The price is low.</p>
}
</body>
</html>
4、switch条件:
@{
var weekday=DateTime.Now.DayOfWeek;
var day=weekday.ToString();
var message="";
}
<html>
<body>
@switch(day)
{
case "Monday":
message="This is the first weekday.";
break;
case "Thursday":
message="Only one day before weekend.";
break;
case "Friday":
message="Tomorrow is weekend!";
break;
default:
message="Today is " + day;
break;
}
<p>@message</p>
</body>
</html>
浙公网安备 33010602011771号