I asked how to render a UserControl's HTML and got the code working for a dynamically generated UserControl.
Now I'm trying to use LoadControl to load a previously generated Control and spit out its HTML, but it's giving me this:
Control of type 'TextBox' must be placed inside a form tag with runat=server.
I'm not actually adding the control to the page, I'm simply trying to grab its HTML. Any ideas?
Here's some code I'm playing with:
TextWriter myTextWriter = new StringWriter();
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);
UserControl myControl = (UserControl)LoadControl("newUserControl.ascx");
myControl.RenderControl(myWriter);
return myTextWriter.ToString();
You can either add a form to your user control, or use a regular html input box
Edit: If you are trying to do something AJAXy, maybe you want something like this http://aspadvice.com/blogs/ssmith/archive/2007/10/19/Render-User-Control-as-String-Template.aspx
You can remove the data binding part if not needed.
You can add the control into page, render html and then remove the control from page.
Or try this:
This is a dirty solution I used for the moment (get it working then get it right, right?).
I had already created a new class that inherits the UserControl class and from which all other "UserControls" I created were derived. I called it formPartial (nod to Rails), and this is going inside the public string renderMyHTML() method:
Drawbacks off the top of my head:
It'd be easy to mess up 1 or 2. Hopefully, though, this helps someone else come up with a more elegant solution.
Alternatively you could disable the ServerForm/Event-validation on the page that is rendering the control to a string.
The following example illustrates how to do this.
I was having the same problem using similar code to @TcKs and haven't been able to make any of these examples work for me. I got it working by using the
LoadControl
method of aUserControl
as such: