Here is my sample code:
<script type="text/javascript">
$(function () {
$('body')
.append('<form id="form1"></form>'); //append a new form element with id mySearch to <body>
$('#form1')
.attr("runat", "server")
.append('<asp:Button runat="server" ID="btn1"/>');
});
</script>
This is how my body tag looks like:
<body>
</body>
I get this error:
Control 'btn1' of type 'Button' must be placed inside a form tag with runat=server.
Thanks in advance! 🙂
Update: I tried to omit the
.append('<asp:Button runat="server" ID="btn1"/>');
When I run the firebug i get this:
<body>
<form id="form1" runat="server"></form>
</body>
It does have a runat=”server”. Why I can’t place my asp:Button inside it? o_O
Your updated question is is still a wrong approach. You can’t do this:
and expect it to work the same as if you typed this:
because the tag above is processed server side and actually renders on the client side like this:
and that looks nothing like what you are doing.
You have two options:
Stop trying to add any ASP.NET controls (i.e. starts with
<asp:) or anything withrunat="server"in it with Javascript. If you really have to do this with Javascript, then use regular HTML controls.Stop using Javascript and actually correctly use
<asp:controls or HTML controls withrunat="server"and then do what you need to do from the code behind.And now for the tangent.
Concerning your error of
Control 'btn1' of type 'Button' must be placed inside a form tag with runat=server.Let’s say you correctly use<form runat="server">and try again. You may find it (sort of) works!This will render, but it is not correct. Besides being confusing, nasty code, it only works because ASP.NET actually renders the HTML for that
<asp:Buttonand puts it in the script block, so what is sent to the client is this (and two buttons.. but still not what you typed).And now for part you didn’t expect. From the code-behind, you can do this on Page Load:
And instead of having two buttons that say
Button 2andButton 1on the screen, the second button now saysThis is Awful.…but again, this is totally wrong and will break for most other
<asp:controls if you try to do it (and I’m not sure why ASP.NET converts the code in the Javascript block at all). So, see the two options above on how you can proceed.