posted 12/22/2008 6:16:52 AM by Vivek Thakur
In ASP.NET, when we try to add client side script on events such as onclick and onload to controls with runat="server", we will get this error:
Error 1 Too many characters in character literal
For example, see this code:
<form id="form1" runat="server" onload="alert('Will not work!')" >
Compiling it will result in the error above. As another example, see the HTML code below:
<asp:Button ID="Button1" runat="server" Text="Button" onclick="myClientSideMethod()" />
If we try to compile it, we will get this error:
'ASP.new_aspx' does not contain a definition for 'myClientSideMethod'
Now why are we getting such errors? Does this mean we can't add client side code to these server controls? Answer is somewhat simple: notice that this error will only come if the control has a runat="server" attribute, which implies that events such as onclick and onload will correspond to server events instead of any client side code. That's why in ASP.NET 2.0 we have a OnClientClick method for the Button control. That means if we have a control with no runat="server" like:
<input type="button" ID="Button1" value="Button" onclick="myClientSideMethod()" />
then we will not get any such error since onclick event this time would correspond to the client side script only.
Another way to wire client side script to server controls is to add attributes via code, for example:
protected void Page_Load(object sender, EventArgs e){ Button1.Attributes.Add("onclick", "alert('Hi');");}
This would work as expected. As for the <form> tag's onload event, its better to remove it and place onload in the <body> tag instead.
Vivek Thakur (Member since: 11/27/2008 11:54:25 AM) I am one of the administrators at CodeAsp.Net and I love programming, architecting solutions, code reviews, teaching and writing about ASP.NET.
View Vivek Thakur 's profile
Leave a comment
It's fast, easy and free! Submit articles, get your own blog, ask questions & give answers in the forums, and become a better developer, faster.
enter your email address: