Web Forms error message: "This is not scriptlet. Will be output as plain text" - asp.net

In my ASP .NET Web Forms I have the following declarative code:
<asp:TextBox runat="server" ID="txtbox" CssClass='<%=TEXTBOX_CSS_CLASS%>' />
The constant TEXTBOX_CSS_CLASS is defined in a base class that the page's code-behind class inherits from:
public class MyPageBase : Page
{
protected internal const string TEXTBOX_CSS_CLASS = "myClass";
}
The edit-time compiler however warns me that "This is not scriptlet [sic]. Will output as plain text".
True to its word, the css class is rendered as literally "<%=TEXTBOX_CSS_CLASS%>".
What does this error message mean and is there a workaround so I can still use a constant in a base class?

You cannot use <%= ... %> to set properties of server-side controls.
Inline expressions <% %> can only be used at
aspx page or user control's top document level, but can not be embeded in
server control's tag attribute (such as <asp:Button... Text =<% %> ..>).
If your TextBox is inside a DataBound controls such as GridView, ListView .. you can use: <%# %> syntax. OR you can call explicitly DataBind() on the control from code-behind or inline server script.
<asp:TextBox runat="server" ID="txtbox" class='<%# TEXTBOX_CSS_CLASS %>' />
// code Behind file
protected void Page_Load(object sender, EventArgs e)
{
txtbox.DataBind();
}
ASP.NET includes few built-in expression builders that allows you to extract custom application settings and connection string information from the web.config file. Example:
Resources
ConnectionStrings
AppSettings
So, if you want to retrieve an application setting named className from the <appSettings> portion of the web.config file, you can use the following expression:
<asp:TextBox runat="server" Text="<%$ AppSettings:className %>" />
However, above snippet isn't a standard for reading classnames from Appsettings.
You can build and use either your own Custom ExpressionBuilders or Use code behind as:
txtbox.CssClass = TEXTBOX_CSS_CLASS;
Check this link on building Custom Expression builders.
Once you build your custom Expression you can display value like:
<asp:TextBox Text="<%$ SetValue:SomeParamName %>"
ID="setting"
runat="server" />

The problem is that you can't mix runat=server controls with <%= .. %>code blocks. The correct way would be to use code behind: txtbox.CssClass = TEXTBOX_CSS_CLASS;.

This will work.
Mark up
<asp:TextBox runat="server" ID="txtbox" class='<%# TEXTBOX_CSS_CLASS %>' />
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtbox.DataBind();
}
}
But its a lot cleaner to access the CssClass property of the asp:TextBox on Page_Load

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();
}
}

Resources cannot be accessed in aspx page

i have a solution in which i have a web project and couple of other projects. I have added another project that has nothing but a resx file. I have referenced this resource project dll into the web project. is there any possible way i could access the resource in dll into the aspx page. For ex:
<asp:Button ID="Button1" runat="server" Text="<%$ Resources:Resource,ButtonName %>">
The ButtonName must be accessed from the resourcedll.
Import the namespace into the aspx page using #Import page directive.
<%# Import Namespace = "MyProject.Resources" %>
Now to use the resource for setting the property of a Server control, you need to call DataBind() method at the page level on your Page_Load() event. (can be invoked for specific controls also).
Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataBind();
}
}
in your aspx page:
<asp:Button ID="Button1" runat="server" Text = '<%# ProjectResources.CmdBtn %>' />
make sure you make the resource class and the resource key property public, its internal by default.

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