Eval scripts in server side control property - asp.net

how do i implement an eval script in a sever side control?
eg. <a runat="server" href="?id=<%= Eval("Id") %>">hello world</a>

If the server-side control is within a databound control (ListView, GridView, FormView, DetailsView), then the syntax is: <%# Eval("Id") %>.
If the server-side control is not within a databound control, you will have to access it via the code-behind and set your attribute there.

as far as I know, its <%# instead of <%=

The Data-Binding expression is your friend, see MSDN for examples.

Related

asp:hyperlink href won't show up even though i populate navigateurl

Does anyone know what is wrong with the following two lines of code? In both cases, there is no href in the anchor links when i view it in the browser:
<asp:HyperLink runat="server" NavigateUrl='<%# Eval(Request.QueryString["conferenceId"], "~/Cms/schedule-edit.aspx?conferenceId={0}&type=workshopStream") %>' Text="Create Workshop Stream"></asp:HyperLink>
<asp:HyperLink runat="server" NavigateUrl='<%# String.Format("~/Cms/schedule-edit.aspx?conferenceId={0}&type=scheduleItem", Request.QueryString["conferenceId"]) %>' Text="Create Schedule Item"></asp:HyperLink>
This exact same code seems to work fine when I put it into the ItemTemplate of a Listview though. But it doesn't work when used on it's own in an aspx file.
What's wrong with it?
Also if i replace the navigateUrl with a hardcoded string ~/cms/schedule-edit.aspx?conferenceId=2&type=stuff then the href shows up. It just doesn't work when i have the Eval or String.Format in there.
If those HyperLink server controls are located outside of DataBound controls like GridView, there are two problems in our code -
You want to use <%= %> instead of <%# %> which is used in DataBound controls.
You cannot use <%= %> to set property of a server control. Basically, you cannot mix runat="server" with <%= %>.
Solution
<a href='<%= String.Format("~/Cms/schedule-edit.aspx?conferenceId={0}&type=scheduleItem",
Request.QueryString["conferenceId"]) %>'>Create Workshop Stream</a>
The anchor syntax NavigateUrl='<%#...%> is only valid inside a GridView, ListView, etc. When it is not inside such controls, you can set its NavigateUrl property via code. Obviously, you also need to give an ID to your HyperLink.
The markup:
<asp:HyperLink ID="HyperLink1" runat="server" Text="Create Schedule Item"></asp:HyperLink>
The code behind:
HyperLink1.NavigateUrl = String.Format("~/Cms/schedule-edit.aspx?conferenceId={0}&type=scheduleItem", Request.QueryString["conferenceId"])
You are using a data-binding expression here. This is denoted in the following syntax:
<%# [code] %>
The code inside is evaluated only when the containing control, or any of its ancestors have their .DataBind() method called.
To work this around, you can:
Call Page.DataBind()
This could have some unwanted consequences if you have other data-bound controls on the page, as this method will cause all of them to have their data-binding events fired. Usually, this approach is applied if you have minimalistic code-behind and the entire page relies on data-binding expressions.
Give each HyperLink an ID and call HyperLinkID.DataBind();
Stick to the approach in codingstill's answer by setting the NavigateUrl property in the code behind of your page/user control.

Render DateTime.Now directly in the ASPX page

I am trying to do the following directly into the aspx page but it is not showing the date value. I dont want to do it from the code behind. Am i missing something small here? Pls suggest.
<asp:Literal ID="ltrDate" Text='<% DateTime.Now.ToLongTimeString() %>' runat="server"></asp:Literal>
Even the use of hash in the expression <%#DateTime.Now.ToLongTimeString() %> does not work.
If you do not need to access the value of the Literal control from the code-behind, then there is no need to use it. Instead, you can just use the following expression in your page directly where you want to print the date:
<%= DateTime.Now.ToLongTimeString() %>
With server controls, you can only put either static text, databinding expressions <%# xx %>, or expression builders <%$ %> inside the property values in the page markup.
See this related question for more details about each approach.
When using a databinding expression such as <%# DateTime.Now.ToLongTimeString() %>, then you have to call Page.DataBind() (or ltrDate.DataBind() if that's the only databound control) from your code-behind (e.g. in Page_Load).

ASP.NET Code Expression, Data Binding, and other Declarative Expressoins

What are the differences in these tags?
<%
<%#
<%=
<%$
More importantly, how do I display a page property using declarative syntax in an ASP.NET control? I'm trying to do this in an ASP.NET control. The task is to set the text of a label but I do not want to do this pro grammatically in the event I want to change the output control. I get an error about server side controls can't contain this syntax. I'm not sure that I need a databound control for what I want to do but that is another option.
Partial answer coming up.
Update
There is a new tag I've seen in ASP.NET 4.5? site
<%:
Partial answer
quoted from Mike Banavige
<% %> An embedded code block is
server code that executes during the
page's render phase. The code in the
block can execute programming
statements and call functions in the
current page class.
http://msdn2.microsoft.com/en-gb/library/ms178135(vs.80).aspx
<%= %> most useful for displaying
single pieces of information.
http://msdn2.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx
<%# %> Data Binding Expression Syntax.
http://msdn2.microsoft.com/en-us/library/bda9bbfx.aspx
<%$ %> ASP.NET Expression.
http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx
<%# %> Directive Syntax.
http://msdn2.microsoft.com/en-us/library/xz702w3e(VS.80).aspx
<%-- --%> Server-Side Comments.
http://msdn2.microsoft.com/en-US/library/4acf8afk.aspx
Update:
Okay this appears to work
<asp:Label ID="MyLabel" runat="server" Text='<%# MyProperty%>'></asp:Label>
If I use the eval syntax then I get an error about databound control or I use the <% then I get a server side controls error. Any more color appreciated.. not sure I really understand what is going on.
Perhaps it has something to do with the render phase.
Few more observations:
I can use <%= without databinding and get the property value but can not use it in a server side control without getting error.
If I use <%# in server side control but I'm required to do a Page.Databind.
Interestingly, I can use either <%= or <%# when I want to render text that is not inside a control. Although the latter requires databinding.
The new <%: syntax is explained, also called code expression syntax
With ASP.NET 4 we are introducing a new code expression syntax (<%:
%>) that renders output like <%= %> blocks do – but which also
automatically HTML encodes it before doing so.
http://weblogs.asp.net/scottgu/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2
No, server-side controls can't. For example, I have a string property named SkinPath that give me the full App_Themes path to the current theme. I use it in the following way:
<img src='<%= SkinPath %>/Images/myImage.png' />
However, the following doesn't work:
<asp:Image ID='image' runat='server' ImageUrl='<%= SkinPath %>/Images/myImage.png' />
Instead, it renders the src literally in the result <img>.

Two-way data binding of controls in a user control nested inside a FormView doesn't work

I'm trying to perform two-way data binding on the controls in my user control, which is hosted inside a FormView template:
<asp:ObjectDataSource runat="server" ID="ObjectDataSource"
TypeName="WebApplication1.Data" SelectMethod="GetItem" UpdateMethod="UpdateItem">
</asp:ObjectDataSource>
<asp:FormView runat="server" ID="FormView" DataSourceID="ObjectDataSource">
<ItemTemplate>
<uc:WebUserControl1 runat="server"></uc:WebUserControl1>
</ItemTemplate>
<EditItemTemplate>
<uc:WebUserControl1 runat="server"></uc:WebUserControl1>
</EditItemTemplate>
</asp:FormView>
The web user control:
<%# Control Language="C#" ... %>
<asp:TextBox runat="server" ID="TitleTextBox" Text='<%# Bind("Title") %>'>
</asp:TextBox>
The binding works fine when the FormView is in View mode but when I switch to Edit mode, upon calling UpdateItem on the FormView, the bindings are lost. I know this because the FormView tries to call an update method on the ObjectDataSource that does not have an argument called 'Title'.
I tried to solve this by implementing IBindableTemplate to load the controls that are inside my user control, directly into the templates (as if I had entered them declaratively). However, when calling UpdateItem in edit mode, the container that gets passed into the ExtractValues method of the template, does not contain the TextBox anymore. It did in view mode!
I have found some questions on SO that relate to this problem but they are rather dated and they don't provide any answers that helped me solve this problem.
How do you think I could solve this problem? It seems to be such a simple requirement but apparently it's anything but that...
My current workaround for this is, although rather cumbersome, to subclass the FormView class and use subclassed controls in it, implementing my own data binding logic (taking the data field name from a new property) instead of using the <%# %> syntax. Apparently, the code the latter generates is the real culprit here as it doesn't support this nested control scenario.
I ended up, using old asp include statement
<--%include file = "filename" -->
instead of using user controls for dealing with the code duplication issue.

ASP.net Inline Expression Issue

I can't seem to figure out why this does not work below. I need to bind the text box to a value from an inline expression. Seems like a simple thing right? But neither of these work. Any ideas? Thanks in advance.
<asp:textbox id="tbName" runat="server" Text='<%# Eval("test") %>' />
<asp:textbox id="tbName" runat="server" Text='<%= "test" %>' />
Edit:
I should mention that this page has no code behind and only the following directives at the top.
<%# Import Namespace="System" %>
<%# Import Namespace="System.Web" %>
<%# Page Language="C#" %>
Edit:
The only workable solution that I could come up with short of adding a code behind is adding an inline server script, like this one. I wish I knew why the inline expressions won't work unless you're in a data binding context.
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
tbName.Text = "test";
}
</script>
In the Page_Load of you will have to make a call to Page.DataBind() for
<asp:textbox id="tbName" runat="server" Text='<%# Eval("test") %>' />
to work.
<%= %> is a shortened response.Write() and is never valid as an attribute, for any server tag.
<%# %> can be used, only if the conatainer is databound (the page in your case).
<%$ %> can be used to access data in resources files.
EDIT: You can also take a look at How to 'bind' Text property of a label in markup which is a smimilar question.
As stated, <%= %> is illegal anywhere within a server control declaration, except where inner markup is being parsed as content (eg <ItemTemplate> within a Repeater).
<%# %> is valid as an expression for control properties, as these expressions will be evaluated when DataBind() is called on the control.
Your use of Eval() looks a little suspect though. Per the example, Eval() will use the current Page object as the binding context, which means that the value of the public property named "test" will be bound to when DataBind() is called. Unless you actually have this property defined on the Page class, the expression will never evaluate to anything.
Eval() is mainly intended for use in expressions within controls such as Repeater, GridView, ListView, etc, where there is a list of data items being bound using templates, and you need a method to be able to access the properties of the current data item.
For all other controls, just use normal code expressions inside a data-binding expression - it's much faster, and more intuitive than Eval(), which relies on runtime reflection.
If you want a more clever alternative using <%$ %> syntax that avoids data-binding altogether, go here:
http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
Use <asp:textbox id="tbName" runat="server" Text='<%# Eval("test") %>' />
and set tbName.DataBind(); in page load event.
For those who are searching for more info about inline expressions, refer to the following links.
ASP.net have the following inline expressions
Embedded code blocks <% ... %>
Displaying expression <%= ... %>
Directive expression <%# ... %>
Data-binding expression <%# ... %>
Expression builder <%$ ... %>
Server-side comments block <%-- ... --%>
You might need the namespace for the textbox control
<%# Import "System.Web.UI.WebControls" %>
Try adding runat="server" to the server elements.
Otherwise, this element will not be processed at server.
EDIT: Actually, "its correct" that this doesn't work; code <%=...%> cannot be evaluated in a server tag, only expressions like for instance <%$ Resources: h1 %>
<asp:textbox id="tbName" runat="server"><%="test"%></asp:textbox>

Resources