2011-09-22 40 views
0

我有以下代碼,我想將表標題放在@foreach之外,但是當我將它移到外面時,它不再看到結束標記。由於獲取不正確的剃刀語法錯誤

@foreach (var item in Model) 
{   
<div class="data" ><label for="fullName" >Name: </label>@item.UserName.Replace('.', '')</div>   
if (Model.Count > 0) 
{ 

<table class="data"> 
<tr>  
    <th> 
     Work Date 
    </th> 
    <th> 
     Change Details 
    </th> 
    <th> 
     Ip Address 
    </th> 
    <th></th> 
</tr> 


<tr>   
    <td>    
    @{ 
    var stringDate = item.WorkDate.ToShortDateString(); 
    } 
     @Html.DisplayFor(modelItem => stringDate) 
    </td> 
    <td> 
     @Html.DisplayFor(modelItem => item.ChangeDetail) 
    </td>  
    <td> 
     @Html.DisplayFor(modelItem => item.IpAddress) 
    </td>  
</tr> 
</table> 
} 
<br /> 
<hr /> 

}

所以這是有點什麼,我試圖完成,但它一直給我的錯誤,不管什麼辦法,我試試吧。

<table class="data"> 
<tr>  
    <th> 
     Work Date 
    </th> 
    <th> 
     Change Details 
    </th> 
    <th> 
     Ip Address 
    </th> 
    <th></th> 
</tr> 

    @foreach (var item in Model) 
{ 

    <div class="data" ><label for="fullName" >Name: </label>@item.UserName.Replace('.','')</div>   
if (Model.Count > 0) 
{ 


    <tr>   
    <td>    
    @{ 
    var stringDate = item.WorkDate.ToShortDateString(); 
    } 
     @Html.DisplayFor(modelItem => stringDate) 
    </td> 
    <td> 
     @Html.DisplayFor(modelItem => item.ChangeDetail) 
    </td>  
    <td> 
     @Html.DisplayFor(modelItem => item.IpAddress) 
    </td>  
</tr> 


</table> 
} 
<br /> 
<hr /> 

}

回答

4

您必須將表格結束標記放在每個循環之外。

+0

哇我覺得無知已經搞亂了20分鐘。謝謝 ) – Jesse

3

短的答案:結束標記</table>必須放置foreach環的


龍答:你應該把Model.Count > 0foreach循環的,因爲時刻,你在循環中輸入代碼塊,Model.Count > 0結果始終爲true,因爲至少有一個項目。

如果 - 並且只有 - 如果 - 您的模型包含任何項目,纔會打印出表頭。之後,您在Model的每個item附加一行。 <table></table>必須在相同的嵌套級別內發生。

@if (Model.Count > 0) 
{ 
    <table class="data"> 
     <tr>  
      <th>Date</th> 
      <th>Change Details</th> 
      <th>Ip Address</th> 
      <th></th> 
     </tr> 

    @foreach (var item in Model) 
    {   
     <div class="data" > 
      <label for="fullName" >Name: </label> 
      @item.UserName.Replace('.', ' ') 
     </div> 

     @{ 
      var stringDate = item.WorkDate.ToShortDateString(); 
     } 

     <tr>   
      <td>@Html.DisplayFor(modelItem => stringDate)</td> 
      <td>@Html.DisplayFor(modelItem => item.ChangeDetail)</td>  
      <td>@Html.DisplayFor(modelItem => item.IpAddress)</td>  
     </tr> 
    } 

    </table> 

    <br /> 
    <hr /> 
} 

,應考慮邏輯(@item.UserName.Replace('.', ' '))從視圖的移動到相應的控制器的動作。