Your updated question is still the wrong approach. You cannot do this:
$('#form1').attr("runat", "server")
and expect it to work the same as if you typed this:
<form runat="server">
because the tag above is processed server side and actually renders on the client side in the following way:
<form method="post" action="default.aspx" id="ctl00">
and it doesn't sound like what you are doing.
You have two options:
-
Don't try to add any ASP.NET controls (i.e. starts with <asp:
) or anything with runat="server"
in it using Javascript. If you really need to do this with Javascript, then use regular HTML controls.
-
Stop using Javascript and actually use <asp:
HTML controls or controls correctly with runat="server"
, and then do what you need to do from code.
And now for the tangent.
Regarding your error Control 'btn1' of type 'Button' must be placed inside a form tag with runat=server.
Let's say you are using it correctly <form runat="server">
and try again. You may find it (sort of) works!
<form id="form1" runat="server">
<asp:Button ID="btn2" Text="Button 2" runat="server" />
<script>
$(document).ready(function () {
$('#<%= form1.ClientID %>').append('<asp:Button Text="Button 1" ID="btn1" runat="server"/>');
});
</script>
</form>
It will show up, but it is wrong. Aside from the obfuscating, nasty code, it only works because ASP.NET actually renders the HTML for this <asp:Button
and puts it in a script block, so what is sent to the client is (and two buttons ... but still not that, what you typed).
<input type="submit" name="btn2" value="Button 2" id="btn2" />
<script>
$(document).ready(function () {
$('#form1').append('<input type="submit" name="btn1" value="Button 1" id="btn1" />');
});
</script>
And now for the part you didn't expect. From the code, you can do this in the Load page:
protected void Page_Load(object sender, EventArgs e)
{
btn1.Text = "This is Awful";
}
And instead of two buttons that speak Button 2
and Button 1
on the screen, the second button now speaks This is Awful
.
... but then again, this is completely wrong and will break for most other controls <asp:
if you try to do this (and I'm not sure why ASP.NET converts the code to a Javascript block at all). So see the two options above about how you can proceed.