Haw can i use a value from a session variable within the attribute of a control? - asp.net

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"] %>' />

Related

Is it possible to use DataBinding to evaluate Controls on .aspx page?

I'm not sure if I am asking this question correctly. I know that I can accomplish what I need in code behind, but I'm wondering if this is possible. I want to hide a control if there is a value in another control. I know I can use databinder.eval in a repeater, but can I use it just for a normal asp control on the page?
In other words, I want to do something like this:
<asp:TextBox runat="server" ID="ConditionalText" Text="Show if other value is empty" Visible ='<%# testValue.Text != "" ? false : true %>'></asp:TextBox>
<asp:TextBox runat="server" ID="testValue"></asp:TextBox>
I tried just the way I have it above, and <%# testValue. exposed available properties of "testValue" TextBox so I thought it might work. It didn't throw any errors but it did not show/hide the textbox. I'm just wondering if this is possible and what I would have to do to accomplish this.
Any assistance is greatly appreciated.
It can work, but since you are using a databinding expression outside a GridView, Repeater etc. you have to call it manually.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//rest of the code
}
//call databind manually
DataBind();
}
PS better to use IsNullOrEmpty instead of = ""
<asp:TextBox runat="server" ID="ConditionalText" Text="Show if other value is empty"
Visible='<%# !string.IsNullOrEmpty(testValue.Text) ? false : true %>'></asp:TextBox>

Settings the ImageUrl in an ImageButton on a master page with an AppSettings key

I'm trying to display the ImageUrl of an asp:ImageButton using AppSettings in my master page like this:
View.Master:
....
<asp:ImageButton ID="aspShowHideButton" ImageUrl='<%# System.Configuration.ConfigurationManager.AppSettings("HomeDirectory").ToString()%>images/arrowUpButton.gif' runat="server" />
Unfortunately when I pull this up in the browser, this is the code that's being rendered:
<input type="image" name="ctl00$ctl00$aspContentMain$aspShowHideButton" id="aspContentMain_aspShowHideButton" onmouseover="ShowHideButtonMouseOver()" onmouseout="ShowHideButtonMouseOut()" src="../%3C%25#%20System.Configuration.ConfigurationManager.AppSettings(%22HomeDirectory%22).ToString()%25%3Eimages/arrowUpButton.gif" />
So it's taking my ImageUrl literally, but I want it to take the value of the key, which is:
...
<appSettings>
....
<add key="HomeDirectory" value="/" />
....
I've tried, removing the "ToString()" function, I've tried "#" and "$" infront of the System.Configuration.... statement. I've also tinkered with trying to get this to work in the Page_Load function, using:
Protected Sub Page_Load(....)
If Not IsNothing(Master.FindControl("aspShowHideButton")) Then
Dim ShowHideButton As ImageButton = Master.FindControl("aspShowHideButton")
ShowHideButton.ImageUrl = System.Configuration.ConfigurationManager.AppSettings("HomeDirectory") + "images/arrowUpButton.gif"
End If
But that didn't seem to work either, I'm assuming because it could not find the control I was looking for (ie. aspShowHideButton).
Fundimentally, i want to have a key/value pair in my web.config file that allows me to change where my images are, and I want to be able to use this key/value pair in an ImageButton:ImageUrl on my master page, which seems like it must be a pretty popular thing to do. Any advise, direction, is appreciated!
Thanks!
For using appsettings in a server tag, use this syntax:
<%$ AppSettings:HomeDirectory %>
But you won't be able to concatenate the sufix of ImageUrl. Notice that if you want to refer home directory in an asp.net server control, ~ will do the trick.
<asp:ImageButton ID="aspShowHideButton" ImageUrl="~/images/arrowUpButton.gif" runat="server"/>
The easy solution
Initialize the ImageUrl property on server side code, say for example the Page_Load event. There you will be able to use whatever server code you want.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.aspShowHideButton.ImageUrl = System.Configuration.ConfigurationManager.AppSettings("HomeDirectory").ToString() + "images/arrowUpButton.gif";
}
}
Now, if you really need to define that sort of concatenation in the ImageButton tag directly, you will need to use the Code Expression Builder. Read about that here.
With Code Expression Builder, you will be able to use this kind of syntax in your ImageButton tag:
ImageUrl="<%$ Code: System.Configuration.ConfigurationManager.AppSettings("HomeDirectory").ToString() + "images/arrowUpButton.gif" %>"
You can try this:
<asp:ImageButton runat="server" ImageUrl="<%$ AppSettings:FullPath %>images/image001.jpg" ></asp:ImageButton>
(Or) there is a small work aroud for this to work:
Web.Config:
<appSettings>
<add key="testKey" value="images/up.gif" />
</appSettings>
Add an image button:
<asp:ImageButton ID="ImageButton1" runat="server" />
And from codebehind you can call this way:
protected void Page_Load(object sender, EventArgs e)
{
this.ImageButton1.ImageUrl = ConfigurationManager.AppSettings["testKey"];
}

<%# Eval("Name1.Text")%> is empty

<asp:Literal ID="Name1" runat="server">Item Name</asp:Literal>
<asp:LinkButton runat="server" EnableViewState="false" Text='<%#Eval("Name1.Text")%>' />
Why Eval() returns empty ?
Thanks.
You are able to Eval controls that were Databound. If you call Page.DataBind you can eval all controls which NamingContainer is the Page.
If you for example DataBind a Gridview, you could eval controls in GridRows.
The time you might want to pass dynamic value as command argument is when it is inside of a databound control.
If it is stand alone control you don't need to pass those values as command argument but simply access them directly inside the Click or OnCommand Event.
If the control is inside of a DataBound control you can set the Command argument in the code-behind.
You could debug it by handling the databinding event of whatever you're trying to databind and taking a look at the variable you're after in that context. Often trying to look at the variable in debug mode will make it very obvious what the problem is.
I don't think that control will be rendered in time.
Do it in code behind.
protected void Page_Init(object sender, Eventargs e)
{
lnkButtonID.Text = Name1.Text;
lnkButtonID.CommandArgument = Name1.Text;
}
In fac I would like to do this :
<asp:ImageButton runat="server" ID="addToCartIMG" OnCommand="btnAdd_Click" EnableViewState="false" CommandArgument='<%# itemId1.Value + ";" + Name1.Text %>' ImageUrl="<%$Resources:MasterPage, Image_AddToCart%>" />
where Item1 is hiddenField and Name1 a literal.
When I debug the method btnAdd_Click, the CommandEventArgs is empty.

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");
...
}

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.

Resources