Assigning Visible Property of the Button to a Static Method Result - css

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") %>

Related

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>

problems with binding <%# in Custom Control

so I've finally started building custom controls instead of using functions which return chunks of HTML ;) But I'm running into a problem. I want to pass parameters to the control, say, "X":
<some:MessageControl runat="server" X=<%# "asd" %> />
My code behind looks like this:
public partial class MessageControl : System.Web.UI.UserControl
{
String x = "";
public String X
{
get { return x; }
set { x = value;}
}
}
When I output the value of x in the control,
x: <%= X %>
it is empty.
If I pass on "asd" directly as in
<some:MessageControl runat="server" X="asd" />
X gets the correct value.
What's happening here? How can I get this to work? Any suggestions are appreciated,
Nicolas
Edit: Some more context. Basically I want to be able to insert the control on a number of pages without settings its properties in the code behind, but still be able to set its visibility by calling a (varying) method from the containing page.
<%# Page Language="c#" Src="MyPage.aspx.cs" AutoEventWireup="true" Inherits="MyPage" %>
<%# Register Src="MessageControl.ascx" TagName="MessageControl" TagPrefix="some" %>
<html>
<body>
<some:MessageControl runat="server" Visible=<%# SomeBoolMethodFromContaining Page%> />
</body>
</html>
For <%= SomeMethods or Property %> expression you need to call DataBind() method in parent page or control that contains this expression on OnPageLoad event or another.
For example here code behind:
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
protected string Hello
{
get { return "hello";}
}
Here html part of the page:
<asp:Literal runat="server" Id="Literal1" Text="<%= Hello %>"/>
For Visible property use code above and <%# Method or Property%> expression. For text use <%= %> expression. It renders output as a plain text.
Hope it will help you with your question.
Best regards, Dima.
Use this:
X='<%# "asd" %>'
Note the single quotes.

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

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.

Can I use <%= ... %> to set a control property in ASP.NET?

<asp:TextBox ID="tbName" CssClass="formField" MaxLength="<%=Constants.MaxCharacterLengthOfGameName %>" runat="server"></asp:TextBox>
The code above does not work. I can set the MaxLength property of the textbox in the code behind but i rather not. Is there away I can set the MaxLength property in the front-end code as above?
You could use DataBinding:
<asp:TextBox
ID="tbName"
CssClass="formField"
MaxLength="<%# Constants.MaxCharacterLengthOfGameName %>"
runat="server">
</asp:TextBox>
and in your code behind Page_Load call:
tbName.DataBind();
or directly databind the page:
this.DataBind();
The <%= expression %> syntax is translated into Response.Write(expression), injecting the value of expression into the page's rendered output. Because <%= expression %> is translated into (essentially) a Response.Write these statements cannot be used to set the values of Web control properties. In other words, you cannot have markup like the following:
<asp:Label runat="server" id="CurrentTime" Text="<%= DateTime.Now.ToString() %>" />
Source: https://web.archive.org/web/20210513211719/http://aspnet.4guysfromrolla.com/articles/022509-1.aspx
Try to use custom expression builder:
// from http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : System.Web.Compilation.ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}
And then use it like
<asp:TextBox ID="tbName" CssClass="formField" MaxLength="<%$ Code: Constants.MaxCharacterLengthOfGameName %>" runat="server"></asp:TextBox>
As Ropstah said, it isn't going to work with the <%= expression %> syntax.
But you could probably use databinding, which just requires that you use the <%# expression %> syntax and then call MyTextBox.Databind in CodeBehind.
Of course, at that point it might be more clear to just do the whole operation in CodeBehind.
Another alternative: if you really want this to be declarative, you could get away from the Label and embed your expression in a span tag.That way you still get to apply CSS, etc and I think the <%= expression %> syntax would work.
Why don't you just set it in the Page_Init callback function in the code behind?
This example is geared towards getting the max length from underlying sql types in linq. But you should be able to customise it to your needs
http://blog.binaryocean.com/2008/02/24/TextBoxMaxLengthFromLINQMetaData.aspx
It looks like you want to be able to control the max length of a specific type of text box from a single location so that if that max length needs to change, you only need to change it in one place.
You can accomplish this by using a skin file. You set the max length in the skin file as you would normally and then any textbox that uses that max length would use the skin. If the length changes then you only need to change the skin file.
You can do it with databinding
<asp:TextBox
ID="tbName"
CssClass="formField"
MaxLength='<%# Constants.MaxCharacterLengthOfGameName %>'
runat="server" />
Then in the code behind
protected void Page_Load(object sender, EventArgs e) {
Page.DataBind();
}
You can embed "normal" code in the .aspx file if you so want, like:
<%
tbName.MaxLength = Constants.MaxCharacterLengthOfGameName
%>
<asp:TextBox ID="tbName" CssClass="formField" runat="server"></asp:TextBox>
This harkens back to an older style "classic" ASP way of doing this.

Databind Function to Controls Visible Property Does Not Work

I'm using databinding to set the visible property on a control as such:
Control on Page:
<asp:LinkButton ID="ApproveTimeLink" runat="server" Visible="<%# CanApprove() %>"> Approve Time</asp:LinkButton>
Code on CodeBehind:
Protected bool CanApprove()
{
return false;
}
As you can see the control should not show, yet still does. I'm not getting any errors, and I'm baffled as to why this does not work.
Thanks for the help.
all you have to this is the following
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
}
public bool CanApprove()
{
return false;
}
then you can use this method on the asp-control as you mentioned before!
but be we aware! Every property of the page has to be not null, otherwise the databind will fail with an exception!
Sometimes you cannot set control properties with <%# %> and you have to resort to using OnItemDataBound(...) to get a reference to the control and set its Visible property there. Another thing that sometimes can be an issue is nested quotes, but in your sample code I don't see that as a problem. If your real code includes nested quotes, like Visible="<%# CanApprove(Eval("ID"))%>" then that may be your real issue. You can get around this by using single quotes and alternating with double quotes.
This worked great for me too... thanks!!
<asp:Label runat="server" ID="lblLocaton" Text='<%# String.Format("{0}, {1}", Eval("City"), Eval("Region.Code")) %>' Visible="<%# ShowLocation() %>" />
AND
MfnPresenter.Website.Presenters.IInstituitonListView.ShowLocation
Get
End Get
Set(ByVal value As Boolean)
'Used by visibility binding expression on lblLocation control inside dlFinancialInsitution
End Set
End Property

Resources