简体   繁体   中英

How to show and hide div tag in Index.csthml in ASP.NET C#?

I have a bool in my ViewModel.cs

public bool HasPackType { get; set; }

Summary & Question

So the idea is simple, if HasPackType is true, hide the div tag in Index.cshtml.

I know there are many ways to hide stuff in index.cshtml, but for this particular situation, to keep it simple, I would like to hide the div without JavaScript code.

I have tried this:

  <div class="form-group spaced" style=@(Model.HasPackType;) "display: none;">
                            
   </div>

Still cannot hide the div when my program is running so I wonder if I am thinking "right" with this solution?

Thanks!

if you don't want use JS, this code solve your problem.

     <div class="form-group spaced" style="@(Model.HasPackType ? "display: none;" : "" )" >
                             
     </div> 

and if you don't want Generate html you can use this:

@if (!Model.HasPackType){
    <div class="form-group spaced">
    </div>
}

The problem you've got is that you're not generating valid HTML and could probably use the ternary operator

<div class="form-group spaced" style="@{ Model.HasPackType ? "display: none;" : string.Empty }">
</div>

This way you're free to unhide it in JavaScript later.

However, if you don't even want the div in the markup at all you could wrap it with an @if

@if (!Model.HasPackType){
    <div class="form-group spaced">
    </div>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM