Razor:從aspx到cshtml常見錯誤及正確書寫方法

來源:互聯網
上載者:User

從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可測試,不知道如何?,拭目以待。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.