现在的位置: 首页 > 综合 > 正文

从aspx到cshtml常见错误及正确书写方法

2013年01月17日 ⁄ 综合 ⁄ 共 1339字 ⁄ 字号 评论关闭

从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可测试,不知道如何实现,拭目以待。

抱歉!评论已关闭.