akd
akd

Reputation: 6758

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

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?

Upvotes: 55

Views: 145781

Answers (5)

mosborn1987
mosborn1987

Reputation: 69

This seemed to work for me....

<div style="@(Model.YourBoolean?"":"display: none;")">

Upvotes: 1

phn
phn

Reputation: 1820

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

Upvotes: 4

kristianp
kristianp

Reputation: 5895

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

Upvotes: 4

Yuri
Yuri

Reputation: 1861

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.

Upvotes: 42

Shyju
Shyju

Reputation: 218732

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

Upvotes: 110

Related Questions