Razor语法不按我预期的方式工作

时间:2011-03-14 20:43:29

标签: asp.net-mvc-3 razor

我的剃刀语法有些麻烦

给出了一个Parser错误 foreach块缺少结束“}”字符

<ul>
@{var client = "null";}
@foreach (var instance in Model)
{
   if (instance.tbl_Policy.tbl_Client.txt_clientName != client)
   {
       client = instance.tbl_Policy.tbl_Client.txt_clientName;
      </ul><h1>@client</h1>   
      <ul>
   }
   <li>
    @instance.tbl_Policy.txt_policyNumber - 
    Assigned to : @instance.aspnet_Membership.aspnet_User.UserName
    @instance.ATLCheckType.Question
   <button type="button" rel="<%:instance.ATLCheckInstanceId.ToString()%>">DelFiled</button>
   <button type="button" rel="<%:instance.ATLCheckInstanceId.ToString()%>">DelLineItem</button>
   </li>  
}
</ul>

3 个答案:

答案 0 :(得分:7)

Razor无法处理代码块中的不平衡HTML标记。

更改if块,将不平衡标记视为纯文本:

   if (instance.tbl_Policy.tbl_Client.txt_clientName != client)
   {
       client = instance.tbl_Policy.tbl_Client.txt_clientName;
      @:</ul><h1>@client</h1>   
      @:<ul>
   }

答案 1 :(得分:7)

应重构代码以正确支持平衡标记

@foreach (var groupedClient in Model.GroupBy(i => i.tbl_Policy.tbl_Client.txt_clientName))
{
   <ul>
   <h1>@groupedClient.Key</h1>

   foreach(var instance in groupedClient)
   {
       <li>
       @instance.tbl_Policy.txt_policyNumber - 
       Assigned to : @instance.aspnet_Membership.aspnet_User.UserName
       @instance.ATLCheckType.Question
       <button type="button" rel="@instance.ATLCheckInstanceId.ToString()">DelFiled</button>
       <button type="button" rel="@instance.ATLCheckInstanceId.ToString()">DelLineItem</button>
       </li>
   }
   </ul>
}

答案 2 :(得分:2)

那里的所有<%: %>内容都是什么?您需要使用@语法。

<ul>
@{var client = "null";}
@foreach (var instance in Model)
{
   if (instance.tbl_Policy.tbl_Client.txt_clientName != client)
   {
       client = instance.tbl_Policy.tbl_Client.txt_clientName;
      </ul><h1>@client</h1>   
      <ul>
   }
   <li>
    @instance.tbl_Policy.txt_policyNumber - 
    Assigned to : @instance.aspnet_Membership.aspnet_User.UserName
    @instance.ATLCheckType.Question
   <button type="button" rel="@instance.ATLCheckInstanceId.ToString()">DelFiled</button>
   <button type="button" rel="@instance.ATLCheckInstanceId.ToString()">DelLineItem</button>
   </li>  
}
</ul>