Use if condition in ascx file
Asked Answered
L

3

10

Hi, I want to use if condition in .ascx file. As shown below:

<%= if (value.equals("xyz")) {}  %>

as shown above, if i use like that. then i am getting error of "invalid expression if".

please guide me.

Lubow answered 28/7, 2011 at 11:10 Comment(0)
S
17

Instead of <%= you should use <% (without the = sign):

<% if (value.equals("xyz")) { } %>

<%= is used when you want to output the result of the expression directly to the HTML.

Societal answered 28/7, 2011 at 11:12 Comment(0)
L
5

This is because the expression does not evaluate to a string, that can be included in the markup, so the <%=notation cannot be used. You can do it with the conditional operator:

<%= condition ? "value if true" : "value if false" %>

Or you can insert a code block using this notation:

<% if (value.equals("xyz")) { } %>

Just be aware that you then need to Response.Write any output you want within the curly braces. This is not best practice - try to avoid logic in your markup.

Lampoon answered 28/7, 2011 at 11:13 Comment(0)
P
0

Above answers can not be used for boolean atributes such as "Visible". Instead put this code in the BindData() function.

if (condition) {
    this.pnlMyPanel.Visible = true;
} else {
    this.pnlMyPanel.Visible = false;
}

If you don't tipically use BindData(), put it in Page_Load under

if (!this.IsPostBack) {}

block.

Pathos answered 20/3, 2012 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.