代码之家  ›  专栏  ›  技术社区  ›  Jeff Putz

MVC Razor 3 RC语法:错误还是用户错误?

  •  5
  • Jeff Putz  · 技术社区  · 15 年前

    我想这是显而易见的,但是在我提交bug报告之前,我想知道我没有做错。我使用ASP.NET MVC3 RC和Razor来查看:

    <div class="miniProfile">
        Joined: @FormatTime(Model.Joined)<br />
        @if (!String.IsNullOrWhiteSpace(Model.Location)) {
            Location: @Model.Location<br />
        }
        Posts: @Model.PostCount<br />
        @Html.ActionLink("Full Profile", "ViewProfile", new { id = Model.UserID }, new { target = "_blank" }) | 
        @Html.ActionLink("Send Private Message", "SendNew", "PrivateMessages", new { id = Model.UserID }) | 
        @Html.ActionLink("Send E-mail", "Send", "Email", new { id = Model.UserID })
        @if (!String.IsNullOrWhiteSpace(Model.Web)) {
            | <a href="@Model.Web" target="_blank">Visit user Web site: @Model.Web</a>
        }
    </div>
    

    在最后一个条件下,它在“位置”和管道处阻塞。如果我插入一些“文本”标记,则其工作方式如下:

    <div class="miniProfile">
        Joined: @FormatTime(Model.Joined)<br />
        @if (!String.IsNullOrWhiteSpace(Model.Location)) {
            <text>Location: </text>@Model.Location<br />
        }
        Posts: @Model.PostCount<br />
        @Html.ActionLink("Full Profile", "ViewProfile", new { id = Model.UserID }, new { target = "_blank" }) | 
        @Html.ActionLink("Send Private Message", "SendNew", "PrivateMessages", new { id = Model.UserID }) | 
        @Html.ActionLink("Send E-mail", "Send", "Email", new { id = Model.UserID })
        @if (!String.IsNullOrWhiteSpace(Model.Web)) {
            <text>| </text><a href="@Model.Web" target="_blank">Visit user Web site: @Model.Web</a>
        }
    </div>
    

    尽管有些尝试和错误,我不知道我在做什么,这是淘气。建议?

    2 回复  |  直到 15 年前
        1
  •  7
  •   marcind    15 年前

    您的标记应该如下

    <div class="miniProfile">
      Joined: @FormatTime(Model.Joined)<br />
      @if (!String.IsNullOrWhiteSpace(Model.Location)) {
        <text>Location: @Model.Location<br /></text>
      }
      Posts: @Model.PostCount<br />
      @Html.ActionLink("Full Profile", "ViewProfile", new { id = Model.UserID }, new { target = "_blank" }) |
      @Html.ActionLink("Send Private Message", "SendNew", "PrivateMessages", new { id = Model.UserID }) |
      @Html.ActionLink("Send E-mail", "Send", "Email", new { id = Model.UserID })
      @if (!String.IsNullOrWhiteSpace(Model.Web)) {
        <text>| <a href="@Model.Web" target="_blank">Visit user Web site: @Model.Web</a></text>
      }
    </div>
    

    @if 语句,在curlys之后的任何内容仍被视为“代码”,因此需要使用 <text> 标签或 @: 语法。

    这种行为的原因是,通常情况下,您会在条件中嵌套某种标记,在这种情况下,一切正常:

    @if(condition) {
        <div>Some content</div>
    }
    

    这个 < 当您不希望条件的内容包装在任何标记中时,就可以使用标记。

        2
  •  2
  •   bdukes Jon Skeet    15 年前

    代码块中不能只有纯文本内容,Razor引擎无法确定它是代码还是标记。这就是 <text> 标签在那里,以消除歧义。你是说 < 标签使它工作(这是答案,没有更多的事情要做),或者它仍然不工作 <文本> if 阻止 < 标签)?