Friday, 3 October 2014

Rendering of ASCX files with AJAX



In ASP.NET project, if the developers trying to provide a portal type user experience to avoiding many page refreshes. The solution was to build one page with a ton of divs, which would show or hide based on the user’s selection in the left hand navigation. Server requests for data to be displayed would be performed via a jQuery AJAX request. As you can imagine, the page got to be very unmanageable.
My thought was to break out the individual sections the user would navigate into separate user controls. To avoid a massive page load, these user controls would be loaded in as needed via a jQuery AJAX request already populated from their code behind file.
The first step in doing this is to create an ASHX handler to load the user control. Since ASCX controls are not made to render on their own outside of a page, this handler would have to render the control within a page and then return the html.

Thus, the html within the page just consists of the user control requested with the parameter “control” is returned.  The next step is to make the jQuery AJAX request to call UserControlHandler.

As you can see, the user control requested is TargetUserControl.ascx. You can also add any data the user control might need in the ajax data element, then just pass it to LoadUserControl after it has been stripped out of context.Request.

The next step was handling submission of form elements in of the user controls. If you take a look at the HTML code rendered in the page at this point, you’ll see that the user controls are wrapped in an empty form tag.
 Since this page is supposed to operate like a portal with no page refreshes, we’ll also submit the form contents with ajax serializing the contents of the form tag.

Then within PageName.aspx you define a webmethod to handle the saving of the data.
 The DataParser object is a custom string parser I defined for the project. The method that’s important here is ParseSubmitString which basically splits the serialized string on ‘&’ so that you have a result of key=value strings which can then be parsed.




No comments:

Post a Comment