views:

81

answers:

2

I want have two columns and based on a condition, include or remove a third. using all the if statements seems a bit redundant. Is there another way to do this?

<table style="width: 60%;">
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Other</th>
                </tr>
                <tr>
                    <td><%= Model.Name.ToString().Trim()</td>
                    <td><%= Model.Age.ToString().Trim()</td>
                    <td><%= Model.Other.ToString().Trim()</td>
                </tr>

                <tr>
                    <td><%= Model.Name2.ToString().Trim()</td>
                    <td><%= Model.Age2.ToString().Trim()</td>
                    <td><%= Model.Other2.ToString().Trim()</td>
                </tr>

                <tr>
                    <td><%= Model.Name3.ToString().Trim()</td>
                    <td><%= Model.Age3.ToString().Trim()</td>
                    <td><%= Model.Other3.ToString().Trim()</td>
                </tr>
            </table>
A: 

if you are using table then hide the column showing Other value:

<% for(......){
    //evaluate here if you will show it or not?
    var showOther = Age > 18 ? "block":"none";
%>
<tr><td>..</td><td>..</td><td display="<%= showOther  %>">..</td></tr>
<% }%>
TheVillageIdiot
+1  A: 

The Ternary conditional operator (?:) makes things look a little nicer if you want to inhibit display of values in a column.

<%= Model.MyValue == somevalue ? "": Model.MyValue.ToString() %>

But if you want to remove the entire column, rather than inhibiting the display of the values, then if statements are perfectly fine.

<tr>
    <td><%= Model.Name.ToString().Trim() %></td>
    <td><%= Model.Age.ToString().Trim() %></td>
    <% if (myCondition) { %>
        <td><%= Model.Other.ToString().Trim() %></td>
    <% } %>
</tr>

By the way, it appears from your code sample that you need a loop. You could also benefit from some Html encoding. Something like this:

<% foreach (Person item in Model) { %>
    <tr>
        <td><%= Html.Encode(item.Name) %></td>
        <td><%= Html.Encode(item.Age) %></td>
        <% if (myCondition) { %>
            <td><%= Html.Encode(item.Other) %></td>
        <% } %>
    </tr>
<% } %>
Robert Harvey