Search code examples
sitefinity

ASP.NET MVC Razor view hide table column


I am building a table in a view and only wanted this column to he visible if the mode is true? Is the if the only way to do this or is can I use something like hide , isvisible or @Html.HiddenFor?

@if(Model.IsLocationMode == true){
          <th>@Html.DisplayNameFor(model => model.Location[0].Name))</th>
   }
    
    @if(Model.IsLocationMode == true){
          <td>@obj.Name</td>
    }

Solution

  • If you don't care about the data, then just use an empty placeholder to maintain your table structure. Or don't include it at all.

    @if(Model.IsLocationMode == true) {
        <td></td>
    }
    

    If you want to toggle the visibility with JavaScript when the user interacts with your page then use CSS.

    @{
        var hiddenClass = (Model.IsLocationMode ? "hidden" : "");
    }
    
    <td>
        <div class="@hiddenClass">
            @Html.DisplayNameFor(model => model.Location[0].Name)
        </div>
    </td>
    

    And don't forget about the style rule

    .hidden {
        display: none;
    }
    

    Then you can use js to control the visibility in response to an event.

    element.classList.toggle('hidden');