views:

274

answers:

3

I am trying to write an aspx page where I am passing some server side value to the Javascript. The server side tag is changing from <% to &lt;%

<asp:TextBox
    ID="txtOriginalNo"
    runat="server"
    onkeyup="javascript:EnterKeyPress(<%=ibtnSubmit.ClientID%>,event);"
    TabIndex="1"
    MaxLength="13"
></asp:TextBox>

This is getting converted during runtime to:

<input
    name="txtOriginalNo"
    type="text"
    maxlength="13"
    id="txtOriginalNo"
    tabindex="1"
    onkeyup="javascript:EnterKeyPress(&lt;%=ibtnSubmit.ClientID%>,event);"
/>

Can anyone tell me why this is?

A: 

You can't use <%= %> there, inside an attribute of a server-side control. You need to assign the asp:TextBox's onkeyup property differently, something like:

<% myTextBox.OnKeyUp = "javascript:EnterKeyPress(ibtnSubmit.ClientID)"; %>
Justice
Where should i add this Keyup? should it be in Markup or in the code behind?
+2  A: 

You can't use a server tag inside a server control. Set the property from code behind:

txtOriginalNo.Attributes["onkeyup"] = "EnterKeyPress(" + ibtnSubmit.ClientID + ",event);"

Note: Don't use the javascript: protocol in event attributes. It's used when you put Javascript code in an URL, if you use it in an event attribute it becomes a label instead.

Guffa
Thanks Guffa.. Breaking my head from morning. it works perfectly :)
A: 

It gets converted to protect you from XSS (cross-site scripting) vulnerabilities. It is a good thing. You cannot have most types of server tags inside attributes of server tags in ASP.NET.

However, you can use binding, see this question 528006 (Server tag in OnClientClick) for more info:

<asp:TextBox onkeyup="<%# CreateKeypressEvent(Eval(ibtnSubmit.ClientID)) %>">
</asp:TextBox>

protected static CreateKeyPressEvent(string source)
{
    return "javascript:EnterKeyPress('" + source + "', event);";
}
DrJokepu