skip to Main Content

I am creating a location management system using C#, SQL and ASP.NET. I want to hide the card div if either my home base location count, pouch count or bunker count is equal to 0 in my database and show all the locations when the value is < 0. Here’s my code is below.

HTML

    @foreach (var item in Model.allItems)
    {


        <div class="card" style="width: 50px;">
            <div class="card-img-top" src="@item.ImageURL" alt="Card Image Cap"></div>
        </div>

        <div class="card">
            <div class="card-body">
                <div class="card-img-top" src="@item.ImageURL" alt="Card Image Cap"></div>
                <h5 class="card-title"><p>Test</p>@item.Name</h5>
                <h6 class="card-title">@item.ItemType</h6>
                <h6 class="card-title">@item.GroupType</h6>
                <p class="homebase" style="color: black;">@item.HomebaseCount</p>
                <p class="pouch" style="color: black;">@item.PouchCount</p>
                <p class="bunker" style="color: black;">@item.BunkerCount</p>

                <input type="text" class="textBoxHome defaultTextBox" />

            </div>
        </div>

    }

</div>

<script>

        $("#homebase").add("#bunker").add("#pouch").click(function () {
            $('.container-2').fadeTo(500, 1);
            $('.container-1').hide();
            $('.container-3').hide();
            $('.pouch').hide();
            $('.bunker').hide();
            $(function () {
                if ($('.homebase') === '0') {
                    $('.homebase').hide();
                } else {
                    $('.homebase').show();
                }
            });
        });

</script>

2

Answers


  1. Hiding

    Hiding a div can be done with style="display: none;". You want to do this on some condition.

    Example for HomeBaseCount only:

    <div class="card" @Html.Raw((item.HomebaseCount == 0 ? "style='display: none;'" : ""))
    

    Because style is used, the HTML is rendered and you could make it visible with JavaScript later if you like.

    Not rendering the HTML

    If a div should not be rendered (no HTML for that div should be sent to the client), you can use

    @if(item.HomebaseCount != 0 || ..)
    {
        // your div
    }
    

    If all HTML between the braces of the foreach loop should not be rendered you could also use a .Where() statement:

    @foreach (var item in Model.allItems.Where(x => x. HomebaseCount != 0 || ..)
    {
        // more divs
    }
    
    Login or Signup to reply.
  2. Just add a if validation before the div card

    @if (item.HomebaseCount !== 0 || item.HomebaseCount !== 0) 
    {
      <div class="card">
        @* code goes here *@
      </div> 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search