views:

493

answers:

3

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

A: 
myDiv.Style["display"] = 'none';

or

myDiv.Visible = false;

Is this what you want ?

pixel3cs
A: 

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
what if the client has no js?
redsquare
that is when you use the first approach and the second approach if you want it to do using js
Rony
+1  A: 

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
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
cottsak
The solution with View Model is my favorite
eu-ge-ne