Reputation: 51807
I have a table on my ASP.net page something like this:
<table runat="server" id="resultsTable"></table>
I dynamically add content to the table, and it works just fine. However, I want to get the HTML of the table once I've added the dynamic content, i.e. something like this (formatting isn't important, I've just added it)
<table runat="server" id="resultsTable">
<tr>
<td>Hello!</td>
</tr>
<tr>
<td>Goodbye!</td>
</tr>
</table>
I need the result as a string. Obviously I could do some looping and build my own table with the data, but I'd prefer to not do that if at all possible.
Upvotes: 3
Views: 10692
Reputation: 4221
Initially I though to just use the InnerHtml or InnerText methods, but these are not supported on the HtmlTable class.
So what if we use the Render method? Something like this (take from Anatoly Lubarsky)?
public string RenderControl(Control ctrl)
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
return sb.ToString();
}
This method could obviously be cleaned up to handle closing the writers, etc.
Upvotes: 6
Reputation: 11975
Hmm. I'd javascript the table markup to some hidden field (which is a server control) before the form gets posted.
<div id="tablediv">
<table>...</table>
</div>
javascript:
var html = document.getElementById('tablediv').innerHTML;
document.getElementById('hfTableHtml').value = html;
EDIT: And yes, I'd worry about the request validation that is going to happen! You'd have to disable it or substitute those markup elements w/ something else before storing it into the hidden field
Upvotes: 0
Reputation: 25652
I used the following in the OnLoad
method of my page to convert your table to a string of HTML:
string html;
using (var writer = new StringWriter())
using (var xmlwriter = new HtmlTextWriter(writer))
{
this.resultsTable.RenderControl(xmlwriter);
html = writer.ToString();
}
Upvotes: 0
Reputation: 11
There is a couple of way I can think of how to do this. The easy would be to surround the table in a . Then on your vb/C# side simply call hold.innerhtml and it will return a string.
Upvotes: 0
Reputation: 11376
Since your table is a server control, you may use its RenderControl method to obtain the render result:
public static string GetRenderResult(Control control) {
using(StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) {
using(HtmlTextWriter writer = new HtmlTextWriter(sw))
control.RenderControl(writer);
sw.WriteLine();
return sw.ToString();
}
}
Upvotes: 0