Razor Syntax Not working the way I expected

2019-04-09 13:27发布

问题:

having some trouble with my razor syntax

gives a Parsor error saying that The foreach block is missing a closing "}" character

<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>

回答1:

Razor cannot handle imbalanced HTML tags in code blocks.

Change your if block to treat the imbalanced tags as plain text:

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


回答2:

The code should be refactored to correctly support balanced tags

@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>
}


回答3:

What's with all of the <%: %> stuff in there? You need to use the @ syntax.

<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>