1

I am using C# with MVC. I want to set the div visible true/false based on a condition from database in the Get method of Controller.

Please suggest

Prasad
  • 58,881
  • 64
  • 151
  • 199

3 Answers3

3

In Controller:

ViewData["DivIsVisible"] = ...
return View();

// or with ViewModel

public class TheViewModel
{
    public bool DivIsVisible;

    ...
}

...

var model = new TheViewModel { DivIsVisible = true /* false */, ... }
return View(model);

In View:

<script runat="server">
    protected bool DivIsVisible {
        get {
            return ViewData["DivIsVisible"] != null && (bool)ViewData["DivIsVisible"];
        }
    }
</script>

<div <%= DivIsVisible ? "" : "style='display: none'" %>>
</div>

<% if(DivIsVisible) { %>
    <div>
        ...
    </div>
<% } %>

<!--or with View Model -->

<div <%= Model.DivIsVisible ? "" : "style='display: none'" %>>
</div>

<% if(Model.DivIsVisible) { %>
    <div>
        ...
    </div>
<% } %>
eu-ge-ne
  • 28,023
  • 6
  • 71
  • 62
  • fantastic examples. but maybe you should have suggested a preferred method? my preferred would be the 'TheViewModel' class in the controller and the inline style attribute to invoke visibility. +1 – Matt Kocaj Jun 02 '09 at 08:11
  • The solution with View Model is my favorite – eu-ge-ne Jun 02 '09 at 17:48
0
myDiv.Style["display"] = 'none';

or

myDiv.Visible = false;

Is this what you want ?

Sorin
  • 2,258
  • 4
  • 27
  • 45
-2

send the result from the database as part of the View Model

then you can use this syntax

<% if(Model.Property) == "desired value"{%>  
<% RenderPartial("div")%>
<%}%>

the best approach would be to change the CSS property of the div using jQuery analysing the database value

$(function(){ if(<%Model.Property == "desired value"%>) $(div).hide(); });

Rony
  • 9,331
  • 2
  • 22
  • 22