Search code examples
c#javascriptasp.netajaxwebmethod

AJAX best practice for adding html components to a page


I'm new to AJAX/javascript, and I'm not sure what the best approach is for what I'm trying to do.

I'm calling page methods (WebMethods) on my Page using Javascript. The data I'm retrieving is a list of Divs basically.

I don't know how many will be returned, but they need to be inserted into the proper place on the page depending on their content.

I see a couple ways of doing this:

  1. Create a list of HtmlGenericControls and pass them back.
  2. Create a list of Strings, where each String is the entire Div code I want to drop onto the page. (This feels wrong for some reason)
  3. Create simple container objects that have the necessary data in them. Pass those to the page and use them to create the Divs within javascript.

I think any of these could work, but I'd like to follow standard practice. Which would you choose?


Solution

  • Actually, IMHO best pratice would be to return the data from the service, rather than HTML, and build the UI on the client. Typically this is because the same data may be used in different places. Now, PageMethods only return data for that page, so server-side HTML can be OK if not needing reuse, but personally I use JQuery to build the UI on the client and only pass the data; this resorts to less data being transferred over the wire, which increases the speed of the app, and pushes off page rendering to the client's browser.

    HTH.