abstract:Razor的出現(xiàn),使頁面看起更加簡潔,Razor的頁面后綴為:.cshtmlRazor基礎(chǔ)語法:1、代碼注釋: 多行注釋: @*注釋信息*@ 單行注釋: // 注釋 1、代碼體{...}[html] view plain copy @{ var x=100;&
Razor的出現(xiàn),使頁面看起更加簡潔,Razor的頁面后綴為:.cshtml
Razor基礎(chǔ)語法:
1、代碼注釋:
多行注釋: @*注釋信息*@
單行注釋: // 注釋
1、代碼體{...}
[html] view plain copy @{ var x=100; var y=100; string str="this is string"; }
在代碼體中,沒一行都需要用";"結(jié)束,代碼區(qū)中,字母區(qū)分大小寫。字符類型常量必須用""括起來,
2、 由于asp.net引擎會檢解析查每個已@開頭的代碼,除非@前包括非空白字符;如:<div>test@razor</div>
這樣輸出的信息還是test@razor,這不會進行解析,頁面輸出@符合,可以用HTML中的ASCII編碼@。
3、 在Razor中使用局部變量,進行上下文調(diào)用:
[html] view plain copy @{ var message="現(xiàn)在時間為:"; var time=DateTime.Now; var outMessage=message+time; } <div>@outMessage </div>
頁面輸出為:現(xiàn)在時間為:2011/12/14 20:26:13;
4、字符拼接輸出
[html] view plain copy
@{var cout=100;} <p>這是第 @count 個進球 </p>
頁面輸出:這是第 100 個進球
如果頁面要輸出:這是第100個進球
則調(diào)用方式則為:<p>這是第@{@count}個進球</p>,
如果直接用<p>這是第@count個進球</p>,頁面將會直接輸出:這是第@count個進球
如果輸出的是變量的方法名:
<p>這是第@count.ToString()個進球</p>,則可以不用@{}標志
5、 在@{...}代碼體中輸出文字,需要用到@:,如下所示:
[html] view plain copy
@{ var name="張三"; @:你好: @:@name }
頁面輸出:你好:張三
6、 邏輯代碼處理
[html] view plain copy
@{ if(true) { // do something; } else { // do something; } }
7、 在@{...}代碼體內(nèi)部使用html標記
[html] view plain copy
@{ <div>this is <span>test</span></div> }
頁面輸出:this is test
要進行多行輸出時可用:
[html] view plain copy
@{ <text> this first, this secend </text> }
頁面輸出:this first, this secend
8、 在@{...}內(nèi)部使用注釋
[html] view plain copy
@{ // 單行注釋 var mesage = "Now Time:"; @* 當前時間 輸出當前時間 *@ /* * 使用C#中的 * 注釋 */ var time = DateTime.Now; <!-- HTML注釋--> var outMessage = mesage + time; }
9、 數(shù)據(jù)類型轉(zhuǎn)換
[html] view plain copy
AsInt(), IsInt()
AsBool(),IsBool()
AsFloat(),IsFloat()
AsDecimal(),IsDecimal()
AsDateTime(),IsDateTime()
ToString()
@{ var count = "100"; }
<p>count:@count.AsInt()</p> 輸出:count:100 <p>@count.IsInt()</p> 輸出:True 如果 @{ var count = "test"; } <p>count:@count.AsInt()</p> 輸出:count:0 <p>@count.IsInt()</p> 輸出:False
即:AsInt() 如果轉(zhuǎn)換不成功直接為0,IsInt返回Bool值,其他類似
10、循環(huán)使用
[html] view plain copy
@{ /* for循環(huán)使用 */ for(int k=1;k<5;k++) { @:第 @k 個; } @*頁面輸出:第 1 個; 第 2 個; 第 3 個; 第 4 個; *@ // foreach 使用 var list =new List<string> { "one", "two", "three", "four" }; foreach(var str in list) { @:@str; } @*頁面輸出:one; two; three; four; *@ var flag=1; while(flag<5) { @:第@{@flag}個; flag++; } @*頁面輸出:第1個; 第2個; 第3個; 第4個; *@ }