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.
getElementById(\"txtHtmlText\")
So the next time you get the error "Server tag was not well formed" just remember these 3 tips.
-k
Sunday, January 31, 2010
ASP.NET Server tag was not well formed
Labels:
asp.net,
c#,
databind,
inline,
javascript,
Server tag was not well formed
Subscribe to:
Post Comments (Atom)
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.
ReplyDeleteAmazing 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!
ReplyDeleteHey keep posting such good and meaningful articles.
ReplyDeleteHey keep posting such good and meaningful articles.
ReplyDelete