【问题标题】:MVC 4 Razor If splitting div tagsMVC 4 Razor 如果拆分 div 标签
【发布时间】:2013-08-23 15:44:08
【问题描述】:

我有以下 MVC 4 Razor 代码:

@for (int i = 1; i <= 100; i++) {

    if (currentCol == 1) {
        Html.Raw("<div class=row>");
    @*Need to do this because can't have a open div within a if compiler doesnt like it *@
    } if (currentCol == maxCol) {
        Html.Raw("</div>");
    }
    currentCol++;
}

我基本上是在尝试使用 if 语句的不同路径中的开始和结束标记有条件地生成每个 div 类行的内容。当我只使用直接 HTML 时,编译器不喜欢它并认为括号已关闭。 Html.Raw 似乎是我在线搜索的解决方案,但是当我使用Html.Raw 时,当我查看源代码时,div 不显示。

有人知道怎么回事吗?

【问题讨论】:

    标签: asp.net-mvc-4 razor


    【解决方案1】:

    尝试在Html.Raw 调用前加上@

    @for (int i = 1; i <= 100; i++) 
    {
        if (currentCol == 1) 
        {
            @Html.Raw("<div class=row>");
        } 
        if (currentCol == maxCol) 
        {
            @Html.Raw("</div>");
        }
        currentCol++;
    }
    

    【讨论】:

    • 感谢达林做到了 :)
    【解决方案2】:

    Razor 遵循 HTML 和 C#/VB 语法块,这就是分解标签的原因。两种解决方法:

    1:使用Html.Raw(就像你所做的那样)

    if (condition){
      @Html.Raw(@"<div class=""row"">")
    }else{
      @Html.Raw("</div>")
    }
    

    2:使用特殊的&lt;text&gt;...&lt;/text&gt; 标签。

    if (condition){
      <text>
        <div class="row">
      </text>
    }else{
      <text>
        </div>
      </text>
    }
    

    请记住,对于 Razor 解析器,@ 符号意味着您正在从一种语言转换到另一种语言(尽管是 HTML 到代码,反之亦然)。因此,由于您在 if(...) 块中并且 Html.Raw 实际上正在输出 HTML,因此您需要使用 @

    【讨论】:

      【解决方案3】:

      你也可以使用:

      if(condition){
       @:<div>
      }
      
      if(condition){
       @:</div>
      }
      

      【讨论】:

      • 工作正常,由于 Aliment 错误,在“CTRL + K + D”上
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-09
      • 1970-01-01
      相关资源
      最近更新 更多