Monday, October 30, 2006

Getting HTML generated by any control in ASP.NET

Sometimes situation arises in ASP.NET where you want to get the HTML that will be generated by the control without actually rendering the page. For e.g.: When getting the result from an AJAX call, you want to get the HTML generated by say Datagrid, so that you can directly replace the contents of the caller page.

In ASP.NET you can get the HTML of any control by creating a new instance of StringWriter. Using this instance of StringWriter create a new instance of HtmlTextWriter and then rendering the control to this HtmlTextWriter by using RenderControl() method. This method is defined in Control class; therefore every control will have this method. After rendering the control get the HTML from the StringWriter using ToString() method.

Code(C#) is as below:

System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter newHtmlWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
string output = stringWriter.ToString();

If you are rendering a Datagrid or any other control that has a textbox with "runat='server'" tag then this will not work. Because for every textbow with "runat='server'" tag you need to have a "form" with "runat='server'" tag. So if your textbox in Datagrid is a read-only textbox then better replace it with "label" so that the HTML can be rendered correctly.

Changing innerHTML of table row

Few days ago, I got stuck while replacing the innerHTML of a table row with the results from an AJAX call. It happened that IE doesn't support the replacement of contents of a table row, while Firefox and Mozilla allows it.

Googling on the problem, I found that for IE you need to remove all the cells using deleteCell() method. Then create new cell using insertCell() method and then replace the innerHTML of this newly added cell.

So, for replacing the contents of Table in IE you need to iterate over the rows and cells and then replace the content of each cell individually.

For more info: