How to hide a div element depending on Model value? MVC

JqueryHtmlasp.net MvcRazor

Jquery Problem Overview


Here is what I have at the moment

 hidden="@(Model.IsOwnedByUser||!Model.CanEdit)"

This works fine on Chrome but doesnt hide on Internet Explorer

I tried also visibility set false but no luck.

then I found out another style as below

style="@(Model.IsOwnedByUser||!Model.CanEdit)?'display:none'""

I could not get it worked. What is the correct format to hide an element with Razor syntax?

Or I would use Jquery to hide the element. but is it actually possible print out jquery statement that would hide the element on page load?

Jquery Solutions


Solution 1 - Jquery

The below code should apply different CSS classes based on your Model's CanEdit Property value .

<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>

But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.

@if(Model.CanEdit)
{
  <div>Edit/Delete link goes here</div>
}

Solution 2 - Jquery

Try:

<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

Solution 3 - Jquery

Your code isn't working, because the hidden attibute is not supported in versions of IE before v11

If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:

*[hidden] { display: none; }

Solution 4 - Jquery

I know the question is specifically about hiding the div but if you don't do anything else with the div (in JavaScript for example) then you can just not include it in the output of the view by using the Razor @if syntax.

@if (Model.IsOwnedByUser && Model.CanEdit)
{
<div>Some Links</div>
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionakdView Question on Stackoverflow
Solution 1 - JqueryShyjuView Answer on Stackoverflow
Solution 2 - JqueryYuriView Answer on Stackoverflow
Solution 3 - JquerykristianpView Answer on Stackoverflow
Solution 4 - JqueryphnView Answer on Stackoverflow