Razor语法

233 阅读1分钟

Razor视图:
扩展名:.cshtml
@:Razor 语法 ,在@{}中所写的代码都是c#代码

例如:

div>
输出html文本



@{           
string astr = "导航到baidu";
//1.0 利用 Html.Raw ()方法来正常输出html标签
@Html.Raw(astr)


//2.0 利用  MvcHtmlString来正常输出html标签
MvcHtmlString mvcstring = new MvcHtmlString(astr);
@mvcstring
@mvcstring.ToHtmlString()


//3.0  利用 HtmlString来正常输出html标签
HtmlString htmlstring = new HtmlString(astr);
@htmlstring
@htmlstring.ToHtmlString()            
}

       



@@astr= 
@{
//4.0 @: astr 作用:会将@:后面的变量 当做字符串输出   ,注意:@:只能写到@{} 花括号中
//4.0.1 @表示转义符  输出@astr到网页则必须写:@@astr ,只能   @{} 花括号外
@:astr; 
//4.0.2   将包括在其中的变量当做字符串输出,而不是输出变量的值,只能写在@{} 花括号中
astr
}

       



5.0 调用有返回值的方法:
@{ 
string res = MVC.Site.helper.Kits.GetValue("你好");
@res
}


5.0.1 直接使用@@符号即可输出


@MVC.Site.helper.Kits.GetValue("你好啊")


Response.Write()输出 :如果使用@@来调用无返回值的方法则必须将其放入{}中
@{Response.Write(MVC.Site.helper.Kits.GetValue("你好啊11"));}

       



6.0 调用泛型方法
@{
//调用泛型方法获取返回值赋值给resint
int resint = MVC.Site.helper.Kits.GetTResult(100);
//输出结果到屏幕:
@resint
}


6.0.1   直接使用@@()  来调用泛型方法
@(MVC.Site.helper.Kits.GetTResult(12.38m))

       



操作web上下文中的相关对象
@HttpContext.Current

@Response

@@Request.QueryString["id"]=   @Request.QueryString["id"]

@Server

@Session

@Cache

@HttpContext.Current.Server.GetLastError() //gloabl.asmx中的Application_Error()收集当前没有try{}catch{}的异常信息

       



7.0 数据类型转换相关扩展方法

@("123a".AsInt())  等价于  @@{ int.TryParse()}
@("123".IsInt())   结果:true

        @("123.4".AsDecimal())
@("123.4".IsDecimal())



8.0 @@后面有空格的语境
JamesZou@Itcast.us


当@后面有空格的时候 后面的文本会当做变量使用
JamesZou@@ Itcast.us

       



9.0 路径转换 "/home/index"
@@Href("
/home/index")  = @Href("~/home/index")

       



10.0 可以在Razor视图中自己定义方法供Razor调用
@helper  CreateH2(int num)
{
for (int i = 0; i < num; i++)
{

@i


}

}
@CreateH2(5)