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

时间:2013-09-13 09:57:06

标签: asp.net-mvc-3

我是mvc的新手并且正在尝试学习。我希望在ViewBag.Success为空或空时显示表单,但如果ViewBag.Success为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>

我正在运行时收到的错误消息 预计“{”但找到“/”。块语句必须用“{”和“}”括起来。您不能在CSHTML页面中使用单语句控制流语句。例如,不允许以下内容:

我做错了什么不能理解。请帮忙&amp;指南。感谢

1 个答案:

答案 0 :(得分:1)

仅当您的代码包含在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和razor语句。当您在HTML代码之间编写C#代码时,您只需要这样做。但是,当您启动C#代码块时,ASP.NET MVC视图引擎足够智能,可以理解后面的代码是C#,而不仅仅是一些字符串。