How to use ASP.NET <%= tags in server control attributes? - asp.net

This works:
<span value="<%= this.Text %>" />
This doesn't work:
<asp:Label Text="<%= this.Text %>" runat="server" />
Why is that?
How can I make the second case work properly, i.e., set the label's text to the value of the "Text" variable?

Use Data binding expressions
<asp:Label ID="Label1" runat="server" Text="<%# DateTime.Now %>" ></asp:Label>
Code behind,
protected void Page_Load(object sender, EventArgs e){
DataBind();
}

you can do this
<asp:Label ID="Label1" runat="server" ><%= variable%></asp:Label>

You will need to set the value of the server control in code
First of all, assign an ID to the label control so you can access the control
<asp:Label ID="myLabel" runat="server" />
Then, in your Page_Load function, set the value of your labels 'Text' field
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = 'Whatever you want the label to display';
}
This function will be in your code behind file, or, if you are not using the code behind model, inside your aspx page you will need
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = 'Whatever you want the label to display';
}
</script>
Good luck.

In my code i am using something like this easily but in the databound control like ListView Item template
<asp:HyperLink ID="EditAction" class="actionLinks" Visible='<%#Eval("IsTrue").ToString() != "True"%>' runat="server" NavigateUrl='<%# Eval("ContentId","/articles/edit.aspx?articleid={0}")%>' />
But when i tried to use outside the databound control using <%# .. %>, it simply doesn't work.
You can easily do with
My href
But for server controls, and outside of databound control. We need to call DataBind() in pageload event explicitly
<asp:Hyperlink ID="aa" NavigateUrl='<%#myHref%>' >

Not sure how to mark this as such, but this is a bit of a duplicate. See this thread.
I don't think embedding code in to your markup will really make your markup any clearer or more elegant.

<asp:Label> is compiling at runtime and converting to html tags. You can set text with codebehind or like this:
<asp:Label id="Text1" runat="server" />
<% Text1.Text = this.Text;%>
UPD: Seems like my variant doesnt work, this is better:
protected void Page_Load(object sender,EventArgs e)
{
Text1.Text = this.Text;
}

Just pitching this little nugget in for those who want a good technical breakdown of the issue -- https://blogs.msdn.microsoft.com/dancre/2007/02/13/the-difference-between-and-in-asp-net/
I think the crux is in pretty decent agreement with the other answers:
The <%= expressions are evaluated at render time
The <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called.
<%# expressions can be used as properties in server-side controls. <%= expressions cannot.

Related

Set visible of a label from code behind

In asp.net I have this label:
<asp:Label ID="Label3" runat="server" Text="0" visible='<%# visibleCredits() %>'></asp:Label>
In code behind I have:
protected bool visibleCredits()
{
return false;
}
But the label is always shown, it should be invisible I think. Please don't ask why I did not set:
Label3.Visible = visibleCredits();
from the code behind.
Add this to your page:
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
It will bind your page to the server control and allow you to use data bindings like this.
As Vache suggeseted, you need to call DataBind() since you're using the data binding syntax <%# visibleCredits() %>. Alternatively, you can also use <%= visibleCredits() %> and not need to call DataBind().

Call method in ListView EmptyDataTemplate

I have a simple ListView with an EmptyDataTemplate. In the EmptyDataTemplate, there is a LinkButton whose Visble property value is an expression that calls a method in my code behind. The problem is that the LinkButton is always visible regardless of whether the method returns true or false (my method isn't being called as I even set a breakpoint on it). Anyone come across this? What's happening here?
e.g.
<asp:ListView ID="peopleListView" runat="server" ...>
...
<EmptyDataTemplate>
Sorry, no people to view.<br />
<asp:LinkButton ID="newButton" runat="server" Visible='<%# EditPermitted() %>'>New Record</asp:LinkButton>
</EmptyDataTemplate>
</asp:ListView>
In the code behind, I have the method:
protected bool EditPermitted()
{
return false;
}
I don't think you can put scriplets <% %> inside of server controls.
You need to grab the RowDataBound event, and set the link button's visibility there
void gridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.EmptyDataRow) {
LinkButton lb = e.Row.FindControl("newButton");
lb.Visible = EditPErmitted();
}
}
You can't use code blocks like <% ... %> or <%= ... %> inside the attributes of server controls. Only data binding blocks like <%# ... %>. But you can use code blocks inside your EmptyDataTemplate, in this case a simple if statement should work:
<EmptyDataTemplate>
<% if(EditPermitted()) { %>
<asp:LinkButton ID="newButton" runat="server" ... />
<% } %>
</EmptyDataTemplate>

asp.net, enable/disable tabpanel

Why isn't this working?
<ajaxToolkit:TabPanel Enabled='<%# User.IsInRole("admin") %>'...
While this works:
<asp:TextBox Enabled='<%# User.IsInRole("admin") %>'...
Is the first example within a binding context (bound control)? Perhaps you want to use the output directive instead of the binding directive?
<ajaxToolkit:TabPanel Enabled='<%= User.IsInRole("admin") %>'
EDIT: My bad. <%= %> translates into Response.Write, which is not what you want -- too used to ASP.NET MVC, I guess. The best thing is to make it runat="server", give it an ID and set the value in your code-behind.
<ajaxToolkit:TabPanel runat="server" ID="myTabs" ... />
protected void Page_Load( object sender, EventArgs e )
{
myTabs.Enabled = User.IsInRole("admin");
...
}

Haw can i use a value from a session variable within the attribute of a control?

I have an ASP control custom built and I need to pass a value taken from a session variable to it like so:
<custom:control id='mycontrol' value="+Session['myControlValue']+">
...
</custom:control>
the above code obviously doesn't work, I need a way to insert the Session value in the control in this way somehow, can anyone help?
If it is a data bound control you may try this:
<custom:control id="mycontrol"
runat="server"
value='<%# Session["myControlValue"] %>'>
</custom:control>
Personally I would prefer setting this value from the code behind. It seems a little strange to me that a view (aspx) page manipulates the session:
protected void Page_Load(object sender, EventArgs e)
{
mycontrol.Value = Session["myControlValue"];
}
Switch the quotes, like so:
<custom:control id="mycontrol"
runat="server"
value='<%# Session["myControlValue"] %>' />

Assigning Visible Property of the Button to a Static Method Result

I am trying to hide the button based on the user's role using the following code:
<asp:Button ID="btndisplayrole" Text="Admin Button" Visible='<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' runat="server" OnClick="DisplayRoleClick" />
But when I run the above code I get the following error message:
Cannot create an object of type 'System.Boolean' from its string representation '<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' for the 'Visible'
Kind of an interesting issue.. But as the error message states, the string <%= WebApplication1.SiteHelper.IsUserInRole("Admin") %> cannot be converted to a boolean.
Unfortunately i cannot explain why the expression isn't evaluated, but instead is treated like a string.
The reason why your <%# %> expression works as expected, is because it is treated much differently. When the Page is compiled into a class, then the compiler creates an event handler similar to this:
public void __DataBindingButton2(object sender, EventArgs e)
{
Button button = (Button) sender;
Page bindingContainer = (Page) button.BindingContainer;
button.Visible = HttpContext.Current.User.IsInRole("admin");
}
and hooks this method up to the Control.Databinding event on your control. As you can see, the <%# %> is this time properly treated as server code, and not just a random string.
So i guess the solution is either to use databinding, or go to the codebehind as AndreasKnudsen suggests.
As an alternative solution:
<% if (WebApplication1.SiteHelper.IsUserInRole("Admin"))
{%>
<asp:Button ID="btndisplayrole"
Text="Admin Button"
runat="server"
OnClick="DisplayRoleClick" />
<%} %>
The following code worked:
Visible='<%# WebApplication1.SiteHelper.IsUserInRole("Admin") %>'
Note that the aboe use the binding expression!
how about just doing it in the codebehind, for instance on Page_Load ?
public void Page_Load( object sender, EventArgs e )
{
btndisplayrole.Visible = WebApplication1.SiteHelper.IsUserInRole("Admin");
}
Visible='<%= WebApplication1.SiteHelper.IsUserInRole("Admin").ToString() %>'
OR
Visible=<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>

Resources