How do I Remove a table column in MVC?

Asked
Viewd389

0

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>

2 个答案

1

如果要禁止在列中显示值,则三元条件运算符(?:)使事情看起来更好一些。

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

但是,如果要删除整个列,而不是禁止显示值,那么if条语句就可以了。

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

顺便说一句,在代码示例中似乎需要循环。您还可以从一些HTML编码中受益。像这样:

 <% 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>
<% } %>
 
0

如果您使用表格,则隐藏显示其他值的列:

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