In ASP.Net, you can run into unexpected problems when combining embedded script and runat=server controls on the same object. Two resulting problems are:
- Your Html simply won't render (and you'll wonder why)
- You'll get an Html parse error, without it ever even hitting your code behind.
Let's look at a couple such snippets:
Okay: Embedded script doesn't overlap runat=server control.
Problem: This embedded script won't render because it is within the innerHtml of a WebControl (which is obviously runat=server).:
Okay: This does render (within the innerHtml of a runat=server Html control):
Problem: This won't render, because it is within the attributes of a runat=server control:
Big Problem: And this doesn't just render, it gives an Html parse error:
The principles we see here are:
- Try to avoid combining embedded script and runat=server controls for the same object.
- While you may be able to get away with embedded script within the innerHtml of a runat=server HtmlControl, you:
- May run into difficulty putting it in the innerHtml of a WebControl (such as the Text of a Label).
- Should never put it in the attribute of the control itself. If you do need to put it in the attribute, then don't make the control runat=server.