I was working on a problem where in the application was built upon ASP.NET / Javascript. Most of the logic of this highly dynamic application was on the client side javascript. The challenge was that the application was becoming more and more difficult to maintain as the user requirement were adding up.
Which made the javascript files so complex that it was difficult to maintain, even though “jQuery” was used as the framework. The logic was mostly enabling and disabling stuff, updating elements when the user changed something, hiding and displaying the elements.
The application was trying to do a lot of things that a excel spreadsheet does. As the stakeholder wanted the excel spreadsheet to be changed into an application.
Now the main task to do for the application was make it modular and highly maintainable. Since the key thing was javascript to make this application do its task, was something hard to change. Then working on it for a couple of days, came up with the idea of having to make the UI being generated at the server-side since most of the javascript logic was also at the server side (for the initial rendering of the page).
Using this code all I had to do was to call it using ajax and the html content is rendered and sent back as the response.
Below is some code for how to generate the ASP.Net web controls to plain text html.
using System.IO; using System.Text; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace Dilberted.Html { public class DummyPage : Page { public override void VerifyRenderingInServerForm(Control control) { } public override bool EnableEventValidation { get { return false; } set { /* Do nothing */} } } public class HtmlGenerator { public string Generate(WebControl control) { var sBuilder = new StringBuilder(); var sWriter = new StringWriter(sBuilder); var htmlTextWriter = new HtmlTextWriter(sWriter); var page = new DummyPage(); page.DesignerInitialize(); var form = new HtmlForm(); page.Controls.Add(form); form.Controls.Add(control); control.RenderControl(htmlTextWriter); return sBuilder.ToString(); } public string Generate(Control control) { var sBuilder = new StringBuilder(); var sWriter = new StringWriter(sBuilder); var htmlTextWriter = new HtmlTextWriter(sWriter); var page = new DummyPage(); page.DesignerInitialize(); var form = new HtmlForm(); page.Controls.Add(form); form.Controls.Add(control); control.RenderControl(htmlTextWriter); return sBuilder.ToString(); } } }