首先在認識cshtml之前,先要了解一下Razor視圖引擎
如果對此有疑問的話可以借鑒
博客園博文:http://kb.cnblogs.com/page/96883/ 或
博客博文:http://www.cnblogs.com/dengxinglin/p/3352078.html
上面都講解了Razor 以及cshtml的使用語法
這里呢,我們只是整理一下大家熟悉的asp.net和cshtml之間容易出現錯誤的書寫方法
從aspx轉到chshtml還是有很多要適應的地方的,本帖是個人學習筆記帖不斷更新。每天開着本帖編程。
按第一個有意義的編譯錯誤的首字母排序,便於查找:
Cannot implicitly convert type 'void' to 'object'
錯誤:@Html.RenderPartial("_XXXX", Model);
正確:@{Html.RenderPartial("_XXXX", Model);}
其他:這個寫法深刻表明了“<% xxx;%>”這樣的代碼變成了@{xxx;}。
不過感覺這個寫法很丑,是否有更好的?
'object': type used in a using statement must be implicitly convertible to 'System.IDisposable'
錯誤:@using "...";
正確:@using ... ;(把引號去掉)
說明:可以這樣理解,這里的東西除了多了個@之外,都和cs文件中的語法一樣了。
The name 'i' does not exist in the current context
錯誤:
@{
<table>
for (int i = 0; i <= 15; i++)
{
<tr>
//這里用到了i
</tr>
}
</table>
}
正確:
<table>
@for (int i = 0; i <= 15; i++)
{
<tr>
//這里用到了i
</tr>
}
</table>
任何<>都將從C#語法變到html語法,而@{}則相反。
-----------------------------------------------------------------------------------------------
不好:(也能運行)
<td>
@foreach (var user in Roles.GetUsersInRole((string)ViewBag.OldRole))
{
<text>@user<br /></text>
}
</td>
好:
<td>
@foreach (var user in Roles.GetUsersInRole((string)ViewBag.OldRole))
{
@user<br />
}
</td>
說明:@除了能把語境從html變成cs,也能做相反的變化。這樣代碼的簡潔性就好多了。
說明:本以為Razor想把“Html中鑲嵌C#”變成"C#中鑲嵌Html"(類似Helper),看來也不盡然。后者的好處是可以被測試,而前者不行。在推出Razor的時候官網曾經提到要讓Razor可測試,不知道如何實現,拭目以待。