Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Code server-side scripting delimiters / ASP.NET inline expressions in none-ASP elements

Tags:

asp.net

I get this error message:

Cannot create an object of type 'System.Boolean' from its string representation <%: false %> for the 'Visible' property.

When I try to run this code within my ASP.net website:

<a runat="server" visible='<%: false %>' href="~/" >Home</a>

Is there a syntax error? false should be replaceable by any method result same with:

<asp:Panel runat="server" Visible='<%: GetTrueOrFalse() %>'>Home</a>
like image 207
Toshi Avatar asked Sep 08 '17 09:09

Toshi


People also ask

When writing ASP code what are the correct delimiters to use?

ASP.NET (and ASP too) uses the delimiters <% and %> to enclose script commands. Within the delimiters, you can include any command that is valid for the scripting language you are using.

What is an inline expression?

Inline expression is a piece of Groovy code in essence, which can return the corresponding real data source or table name according to the computation method of sharding keys.

What does Runat server mean?

The runat="server" tag in ASP.NET allows the ability to convert/treat most any HTML element as a server-side control that you can manipulate via code at generation time. Some controls have explicit implementations, others simply revert to a generic control implementation.


1 Answers

Suppose you have a method that returns bool value like this:

public bool IsVisible()
{
    if (some_condition) // example condition test
    {
        return true;
    }
    else
    {
        return false;
    }
}

You need to use binding like this:

ASPX

<a runat="server" visible='<%# IsVisible() %>' href="~/" >Home</a>

ASPX.CS (Code-behind)

protected void Page_Load(object sender, EventArgs e)
{
    // do something

    Page.DataBind();
}

NB: This trick apply for either methods or properties which returns bool.

Update 1:

Since a tag doesn't set any id attribute, you can remove runat="server":

<a visible='<%# IsVisible() %>' href="~/" >Home</a>

Or use CSS with display: none or visibility: hidden:

<a visible='<%# IsVisible() %>' href="~/" style="visibility:hidden; display:none;">Home</a>

Reference:

Is code rendering block <%=%> useful for boolean type?

like image 105
Tetsuya Yamamoto Avatar answered Nov 15 '22 06:11

Tetsuya Yamamoto