Can I use <%= ... %> to set a control property in ASP.NET? - 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.

Related

Add text after expression <%$ ... %>

In my ASPX page I've this:
<h3>
<asp:HyperLink runat="server"
NavigateUrl="<%$ Resources:Path, Article%>"
Text='<%# Eval("title") %>' />
</h3>
For the NavigateUrl attribute I want to specify an ID like
NavigateUrl="<%$ Resources:Path, Article%>?id=4"
But when I do that the expression is not precessed by the ASP parser.
How can I do that?
Don't do this in markup. You have a server control here -- give it an ID (say, ID="NavigationLink", and then do something like this in your .cs file:
void Page_Load(object sender, EventArgs e)
{
// I'm guessing that "4" was just an example here, so fill that piece in with a function you can call to create the proper ID.
NavigationLink.NavigateUrl = Properties.Resources.Path + Properties.Resources.Article + "?id=4"
}
Edit: I'm assuming that when you say <%$ Resources:Path, Article%> that you're trying to reference the Path and Article entries in your resources file, but upon further reflection, it's hard to tell exactly what you're doing. Can you be more specific here?
You can define a protected function in the code behind class and call it from the markup. Like this:
<h3>
<asp:HyperLink runat="server"
NavigateUrl="<%# GetNavigateUrl(Eval("ID")) %>" <%-- Passing an ID as a parameter for example --%>
Text='<%# Eval("title") %>' />
</h3>
Code behind:
// Again, idObj is just an example. Any info from the data item can be passed here
protected string GetNavigateUrl(object idObj)
{
int id = (int)idObj;
string urlFromResources = // retrieving the url from resources
return urlFromResources + '?ID=' + id;
}
You could retrieve the resource values programmatically, in your code-behind, and set the NavigateUrl property from there.
Try String.Format...
<% =String.Format({0}?id={1}, Request.ApplicationPath, 4) %>
It looks like you're mixing some other language into this (javascript?).
Also, don't forget to give your server-side controls an ID.

Use of <%= %> and expression databinding for Write Response

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.

problem assigning declarative values in asp:hyperlink. error: this is not scriptlet. will output as plain text

I am trying to do this:
<asp:HyperLink NavigateUrl='<%= WebContext.RootUrl %><%= WebContext.CurrentUser.UserName %>' runat="server" Text='<%= GetProfileImage(WebContext.CurrentUser.AccountId) %>'></asp:HyperLink>
But am getting the error:
this is not scriptlet. will output as
plain text.
when I mouse over my declarative statements.
Any ideas? Thanks.
You cannot use <%= ... %> literals to set properties of server-side controls.
Instead, you can use a normal (client-side) <a> tag, like this:
<%= GetProfileImage(WebContext.CurrentUser.AccountId) %>
If GetProfileImage doesn't return HTML tags, make sure to escape it.
You can use data binding syntax <%# %>. Just be sure that your hyperlink is either in a databound control, such as a ListView item template, or that you explicitly call DataBind() on the control from code-behind.
You can still populate an <asp:HyperLink> if you provide the ID and runat="server" properties. You can then set any property of the HyperLink from code-behind.
ASP Code:
<asp:HyperLink ID="myLink" runat="server"/>
Code-behind:
public void Page_Init()
{
myLink.NavigateURL = WebContext.RootUrl + WebContext.CurrentUser.UserName;
myLink.Text = GetProfileImage(WebContext.CurrentUser.AccountId);
}
<a href='<%= WebContext.RootUrl %><%= WebContext.CurrentUser.UserName %>'><%= GetProfileImage(WebContext.CurrentUser.AccountId) %></a>

Asp.net, directly assigning properties from value?

Is there a way to express
<% objControl.ObjProp=ObjVar; %>
<my:Control ID="objControl" runat="server" />
As something like this, in one line? And without passing ObjVar as a string?
<my:Control ID="objControl" runat="server" ObjProp=ObjVar />
Unless you're in a databound context, no there's no simple way to do this. If it is a databound context (Like in a repeater/gridview) you can simply go ObjProp='<%# ObjVar %>', but outside that context you can't do it inline unfortunately.
use it like
<my:Control ID="objControl" runat="server" ObjProp="<%# ObjVar %>" />
As fyjham has mentioned, you need to do this in a databound context with the <%# %> syntax. If you are trying to set the property dynamically then your other option is to set it within the server side parent's onload code behind method.
What is ObjVar? If it's a static value, you can just add the attribute tag to the control element like so....
<my:Control ID="objControl" runat="server" MyCustomBooleanProperty="true" />
If it's a member variable of the page containing the control, then I'd do so in the code behind...
protected Page_Init()
{
this.objControl.ObjProp = this.ObjVar;
}
If you're databinding to the control, then the others are correct where you use the databinding context.
<my:Control ID="objControl" runat="server" ObjProp=<%#Eval("ObjVar")%> />

Is it possible to use Data-Binding Expressions directly in markup to show/hide content?

I would like to do something like:
<%# if((bool)Eval("IsDisabled")){ %><span>Disabled</span><% }
else { %><span>Active</span><% } %>
but I don't think its possible.
There is a way to create method in codebehind which returns appropriate string and call it, but thats not an option.
You can use placeholders to hold the two versions of your markup and then use the Visible property to show the relevant one. Something like this... Note the use of ! before the call to IsDisabled in the second Visible property.
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible='<%# IsDisabled((bool) Eval("IsDisabled")) %>'>
<span>Disabled</span>
</asp:PlaceHolder>
<asp:PlaceHolder ID="PlaceHolder2" runat="server" Visible='<%# !IsDisabled((bool) Eval("IsDisabled")) %>'>
<span>Active</span>
</asp:PlaceHolder>
The code behind IsDisabled method looks like this...
public bool IsDisabled (bool isDisabled)
{
return isDisabled;
}
Its not possible to use # eval in if statement,
You have some options to solve that:
You can put the condition of the if in a previous line then check on this variable in the if
example:
in code behind:
protected bool isDisabled;
in aspx:
<%# isDisabled=(bool)Eval("IsDisabled") %>
<% if(isDisabled) %>
Other way is to call a code behind method which return bool and check on it in the if.

Resources