I have an ASP textbox control where I need to execute some javascript function when the OnClick event occurs. I need to pass to that javascript function two IDs of other controls on that page. My textbox markup is as follows:
<asp:TextBox ID="txtMonthDisplay" runat="server" Style="border-top: none; border-left: none;
border-right: none; border-bottom: solid 1px blue; cursor: pointer; color: Blue;
width: 35px;" EnableViewState="True" MaxLength="3" onClick="javascript: ShowBox('<%= divYear.ClientID%>', '<%= txtYearDisplay.ClientID %>');"></asp:TextBox>
But whenever it calls the javascript function I have setup an alert to check the incoming values, and they are simply <%= txtYearDisplay.ClientID %> and <%= divYear.ClientID%>. Not the actual IDs of those controls.
What am I missing here, or doing incorrectly? I'm not well versed with asp.net so server vs. client side is a bit fuzzy for me.
Thanks
3 Answers 3
You can't Response.Write
(<%= %>
is shorthand for Response.Write
) into a server tag (usually).
Instead, you can write your onclick handler in the codebehind:
txtMonthDisplay.Attributes["onclick"] = string.Format(
"ShowBox('{0}', '{1}');",
divYear.ClientID,
txtYearDisplay.ClientID);
By the way, you don't need the javascript:
prefix. That is only necessary when setting the href
of a link to execute script. It is not needed for event handlers such as onclick
.
4 Comments
<%# %>
) works in certain circumstances, but I can't remember what those circumstances are. Regarding the jQuery issue, that sounds like a new question. Does the HTML written by ASP.Net contain the actual ClientIds as expected?Then pass the variables from codebehind:
protected void Page_Load(object sender, EventArgs e){
txtMonthDisplay.Attributes.Add("onClick",
String.Format("ShowBox('{0}','{1}')",
divYear.ClientID,
txtYearDisplay.ClientID));
}
The <%= ... %>
displaying expression is an equivalent of the embedded code block that contains only the Response.Write(...)
statement. This is the simplest way to display information such as a single string, an int variable, or a constant.
Remember that the displaying expression cannot be used in the attributes of server controls. This is because the .NET Framework directly compiles the whole expression instead of the displaying content as the value to the attribute.
Comments
Hmm, your markup looks correct, I would try a couple of things, first try adding the onclick event through code and see if the IDs get added. That way you will know if your textbox generation works correctly.
You could also work around by doing click binding after the document.ready using JQuery and having the values as hidden values on the form.