代码之家  ›  专栏  ›  技术社区  ›  Thomas

mvc视图中存在if-else时遇到错误

  •  0
  • Thomas  · 技术社区  · 12 年前

    我是mvc新手,正在努力学习。我想在ViewBag.Success为null或空时显示一个表单,但如果ViewBag.SSuccess为true,那么我想呈现一个部分视图。

    这是我的代码

    <div id="mydiv">
        @if (ViewBag.Success != null && ViewBag.Success == true) //Show the message
        { 
            Html.RenderPartial("Message"); 
        } 
        else 
        {
            @using (Html.BeginForm("Save", "Game", FormMethod.Post, new { @Id = "Form1" }))
            {
                <table border="0">
                    <tr>
                        <td>
                            Name :
                        </td>
                        <td>
                            <input name="name" type="text" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Salary :
                        </td>
                        <td>
                            <input name="salary" type="text" />
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <input name="btnSubmit" type="submit" value="Save" />
                        </td>
                    </tr>
                </table>
            }
        }
    </div>
    

    我跑步时收到的错误消息 应为“{”,但找到了“/”。Block语句必须包含在“{”和“}”中。不能在CSHTML页面中使用单语句控制流语句。例如,以下情况是不允许的:

    我做错了什么无法理解。请帮忙&指导谢谢

    1 回复  |  直到 12 年前
        1
  •  1
  •   U.P    12 年前

    @ 只有当代码包含在HTML元素中时,才需要符号。这个 using 语句不需要 @ 因为它是你的if-else区块的直接继承人。

    例子:

    <div> <!-- html tag -->
        @if(something == somethingElse) // requires @ because direct decedent of html tag <div>
        {
        <p>
            @for (var i=0; i < len; i++) // requires @ because direct decedent of html tag <p>
            {
            if(i == 1) // doesnt require @, not decedent of any HTML tag, instead direct decedent of another razor statement (for)
                {
                    //do something
                }
            }
        </p>
        }
    </div>
    

    这个 @ 符号用于区分简单的字符串/HTML和剃刀语句。只有当您在HTML代码之间编写C#代码时,才需要这样做。但是,当您启动了一个C#代码块时,ASP.NET MVC视图引擎足够智能,可以理解后面的代码是C#,而不仅仅是一些字符串。