Sunday, January 31, 2010

ASP.NET Server tag was not well formed

TIP: ASP.NET C# Expression Language with Javascript

Here's a tip on how to use C# bind code inline with javascript events, first let's use a LinkButton for example:

<asp:LinkButton ID="lnkBtn" runat="server" OnClick="lnkBtn_Click" OnClientClick='<%# "document.getElementById(\"txtHtmlText\").value = " + Eval("id") + ";" %>' />

Imagine this LinkButton is inside a binded control like Gridview or Repeater, etc., now look at the OnClientClick attribute. Remember to be careful with single and double quotes.

1. Use single quotes to contain the whole expresion.

          OnClientClick='  ...  '

2. Enclose inner javascript statements with double quotes and concatenate it with .NET bind statements (like Eval()) with the "+" symbol. 

          "document.getElementById(\"txtHtmlText\").value = " + Eval("id") + ";"

3. Use escaped double quotes (the one with the slash) if ever you'll use double quotes inside another one.


So the next time you get the error "Server tag was not well formed" just remember these 3 tips.



  1. I certainly agree to some points that you have discussed on this post. I appreciate that you have shared some reliable tips on this review.

  2. Amazing blog and very interesting stuff you got here! I definitely learned a lot from reading through some of your earlier posts as well and decided to drop a comment on this one!

  3. Hey keep posting such good and meaningful articles.

  4. Hey keep posting such good and meaningful articles.