Search code examples
c#asp.net-mvcasp.net-mvc-2

Extra If Statements Or Repetative Code in C#


Trying to figure out which makes more sense

<%foreach (var item in Model.items)
   {
%>
<tr>
    <td>
        <% if (!item.isMgmt)
           {  %>
        <a href="/MVC/AzureMail/Unfiled/<%:item.uName %>">
            <%:item.uName%></a>
        <% }
           else
           { %>
        <%:item.uName %>
        <% } %>
    </td>
</tr>
<% } %>

or

 <%foreach (var item in Model.items)
   {
%>
<tr>
    <td>
        <% if (!item.isMgmt)
           {  %>
        <a href="/MVC/AzureMail/Unfiled/<%:item.uName %>">
        <% } %>
              <%:item.uName%>
        <% if (!item.isMgmt)
           {  %>
              </a>
        <% } %>
    </td>
</tr>
<% } %>

Solution

  • 3rd option; an extension method for conditional link.

    public static string ConditionalHyperlink(this HtmlHelper helper, string url, string text, bool shouldLink){
     ...
    }
    

    This keeps your View much more readable.

    <%= Html.ConditionalHyperlink("/MVC/AzureMail/Unfiled/" + item.Name, item.Name, item.isMgmt) %>