Error in resolving server side tag - asp.net

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.

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

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

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

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.

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.

Why is break point unreachable when using jQuery Droplistfilter

I am using this drop list filter on my Asp.Net Form.
jQuery plugin DropListFilter
The filter on the dropdownlist list works perfecty.
<script type="text/javascript">
$(document).ready(function() {
$('select').droplistFilter();
});
</script>
<asp:DropDownList ID="ddlMonth" runat="server" CssClass="ddlStyle"></asp:DropDownList>
<asp:RequiredFieldValidator ID="rfv_ddlMonth" runat="server" ControlToValidate="ddlMonth"
CssClass="warning" Display="Dynamic" ErrorMessage="*" ForeColor=""></asp:RequiredFieldValidator>
<asp:Button ID="btnRun" runat="server" CssClass="btnStyle" OnClick="btnRun_Click" Text="Run Report" />
CodeBehind
protected void btnRun_Click(object sender, EventArgs e)
{
Response.Write(ddlMonth.SelectedValue.ToString());
return;
}
If I do a search on the dropdownlist using the jQuery filter and click run report, the debugger does not stop at the above Response.Write statement.
On application of the filter and pressing Run the debugger does not even hit the load method below.
protected void Page_Load(object sender, EventArgs e)
{
// Bind Month if !PostBack
}
Upon further investigating I am getting the following error on the Application_Error:
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
I do not want to disable the event validation, so what can I do to make the filter work?
The droplistFilter is changing what is being expected by ASP.
ASP doesn't like it when things are changed without it's explicit written consent.
ASP is expecting that dropdown to contain what it put in the dropdown, when you change what is in that with javascript asp sees that as a security risk and is giving you the validation error.

Resources