Use of <%= %> and expression databinding for Write Response - asp.net

i want write content(summary) with <%= %> and expression databinding in below code but do not success!how i can, do it?
<asp:Literal Text='<%# Eval("Summary") %>' ID="SumLitteral" runat="server" />

if you use # sign with the binding expression, then you need to call DataBind() method..
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
DataBind();
}

You can't use the <%= %> syntax to set a property in a server control. You can only use a databinding expression, which you actually have already in your example. Assuming this is part of a Repeater (or some other templated control) and the DataSource is made up of items that have a Summary property, your code above would work. If it's not part of a repeater you can still use a databinding expression, but Eval("Summary") would not have a meaning that makes sense to me, in that case.

If you're saying that the "Summary" value is not actually displaying, its likely that databind() is not being called on the page or the control.

Related

Using Code Nuggets as property values

I have the following code
<asp:Content ID="Content1" runat="server">
<asp:Label runat="server" ID="Label1" Text="<%= MyHelperClass.Value%>"></asp:Label>
<%= MyHelperClass.Value%>
</asp:Content>
The Label doesn't work, it has the Text <%= MyHelperClass.Value%> the next row returns the expected value.
Question: can i use those code nuggets to set values of the property of an control?
Why it's working outside and not with Control?
Well <%= %> is called Content Code Nuggets because they inject content in the html which is sent by server to browser. It does the work of Reponse.Write. We use this mainly to call any code written in code behind file for example, you have a simple method in your code behind:-
public string UserCity()
{
return "London";
}
Then you can call it from aspx page like this:-
You live in <%= UserCity() %>.
Content code nuggets used to inject the html to response at the last in PreRender event and thus it's called late binding. This is the main reason why it is NOT working with your control.
How to fix this?
You can use the data binding code nuggets (<%# %>). These are used with DataBound controls but you can force the Page's DataBound or control's DataBound method to bind your control like this:-
<asp:Label runat="server" ID="Label1" Text="<%# MyHelperClass.Value%>"></asp:Label>
Call DataBind method in code behind:-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Page.DataBind();
}
}

<%# 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.

Error in resolving server side tag

Invalid expression term '<'
<asp:TextBox ID="txtPassword" runat="server"
Width="180px" TextMode="Password"
OnTextChanged="CheckPasswordStrength(<%= txtPassword.ClientID.ToString() %>,<%= lblMessage.ClientID.ToString() %>)"/>
If i writes this code like the following then error occurs An unhandled exception has occured. Server tags cannot contain <% %> constructs
<asp:TextBox ID="txtPassword" runat="server"
Width="180px" TextMode="Password"
OnTextChanged="CheckPasswordStrength("<%= txtPassword.ClientID.ToString() %>","<%= lblMessage.ClientID.ToString() %>")"/>
When I m using this code at .cs file then every thing is working fine.
protected void Page_Load(object sender, EventArgs e)
{
txtPassword.Attributes.Add("onKeyUp", "PasswordCheck("+txtPassword.ClientID.ToString()+")");
txtPrimaryEmail.Attributes.Add("onKeyUp", "EmailChecker("+txtPrimaryEmail.ClientID.ToString()+")");
}
There are a couple things going on with this.. You can't include parameters in your server-side event, and you can't use <%= in a server control.
Are you meaning to fire a JavaScript event?
If you're meaning to fire a JavaScript event, do one of three things:
1) Use a databinding expression (<%# Control.ClientID %>) - This requires that somewhere within the life-cycle DataBind() is being called on your control.
2) Assign the event in the code-behind, using Control.Attributes.Add("javascriptevent", "DoStuff(x, y)")
3) You can use <%= %> in your client script, e.g.
function MyJavaScriptEventHandler()
{
var textbox = document.getElementById('<%= MyASPTextBox.ClientID %>');
alert(textbox.value);
}
I don't think you can include parameters in a Server Event. You will need to reference those controls from the Code-Behind.
Yeah. Server controls cannot contain <% (evaluation for those tags occurs after the server controls - so those tags are considered part of the server control and it fails parsing).
You might want to add the ontextchanged attribute in your code-behind. You could also use JavaScript.

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.

Resources