從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>
正确:
@for (int i = 0; i <= 15; i++)
任何<>都将從C#文法變到html文法,而@{}則相反。
-----------------------------------------------------------------------------------------------
不好:(也能運作)
<td>
@foreach (var user in Roles.GetUsersInRole((string)ViewBag.OldRole))
<text>@user<br /></text>
</td>
好:
@user<br />
說明:@除了能把語境從html變成cs,也能做相反的變化。這樣代碼的簡潔性就好多了。
說明:本以為Razor想把“Html中鑲嵌C#”變成"C#中鑲嵌Html"(類似Helper),看來也不盡然。後者的好處是可以被測試,而前者不行。在推出Razor的時候官網曾經提到要讓Razor可測試,不知道如何實作,拭目以待。
本文轉自火星人陳勇 51CTO部落格,原文連結:http://blog.51cto.com/cheny/1100085