Search code examples
asp.net-mvc-3razorrazor-declarative-helpers

MVC 3 RAZOR coding logic is rendering as text even they are within @{ }


What is wrong with following line of codes?

 <table>
        @{
            string subGroup = "";

            foreach (var item in Model)
            {

                if (item.SubGroupName != subGroup)
                {
                    subGroup = item.SubGroupName;
            <tr style="background-color: #C1E0FF; text-align: left">
                <td colspan="2">
                    @item.SubGroupName;
                </td>
            </tr>
                }
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.configurationitemkey)
                </td>
            <td>
                if (item.IsBoolean)
                @Html.DisplayFor(modelItem => item.IsAvailable)
                else
                @Html.DisplayFor(modelItem => item.ConfigurationItemValue)
            </td>

            </tr>
            }
        }
    </table>

Following code lines render as test even they are within @{ }

<td>
    if (item.IsBoolean)
    @Html.DisplayFor(modelItem => item.IsAvailable)
    else
    @Html.DisplayFor(modelItem => item.ConfigurationItemValue)
</td>

Guide me best way of implementing this type of programming logic in MVC RAZOR

Thanks

@Paul


Solution

  • Have you tried putting an @ before them, because the tag before them is <td> meaning that the Razor parser has switched back to HTML context and not server side code:

    @{
        string subGroup = "";
    }
    
    <table>
        @foreach (var item in Model)
        {
            if (item.SubGroupName != subGroup)
            {
                subGroup = item.SubGroupName;
            }
            <tr style="background-color: #C1E0FF; text-align: left">
                <td colspan="2">
                    @item.SubGroupName;
                </td>
            </tr>
    
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.configurationitemkey)
                </td>
                <td>
                    @if (item.IsBoolean)
                    {
                        @Html.DisplayFor(modelItem => item.IsAvailable)
                    }
                    else
                    {
                        @Html.DisplayFor(modelItem => item.ConfigurationItemValue)
                    }
                </td>
            </tr>
        }
    </table>
    

    Remark: in the example you have shown you don't seem to be using the subGroup variable anywhere in the code, but I am including it anyway as probably that's only a simplified version of your real code and you might need it.