Loading ...

Too many characters in character literal error while adding client side events

 /5
0 (0votes)

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.

Comments (1)

   
Sourabh
Sourabh
it helps me. Thank You
10/31/2009
 · 
by

Top Posts