Web Parts - Best Practices for Rendering Controls
I have recently seen two web parts that contain child controls. The developers saw it fit to either manually render the child controls in the render method or add a heap of literal controls that contain table, tr and td tags. My first question is whether there is a specific reason to take this approach? My gut feel is that the developer saw a web part coded that way in some SharePoint 101 or web parts 101 book or course and has continued to go with that approach ever since. To me this is as ridiculous as coding an ASP.NET page with only Literal controls and embedding the HTML and dynamic content in the literal control. Wouldn't it be better to simply code the entire thing in ASP?
So what is the right approach to coding a web part? I would assume that a lot of the rules around developing an ASP.NET custom server control would apply here as well. My preferred approach is to add items to the pages controls collection (or some other collection on the page) and allow ASP.NET to render it out. Rather than using Literal controls, create Table, TableRow and TableCell objects. Add the Table to the relevant container object's Controls collection (this might be the page itself or a Panel or possibly another containing table). Next add a TableRow object to the newly created Table object and similarly add the necessary TableCell objects to the relevant TableRow.
Though the above method seems time consuming it is definitely less troublesome than relying on manually laying out the web part using literal controls.
Another option is to just use a Web User Control (.ascx file) and embed it inside a web part shell. This takes away the need to programatically layout the controls on the web part. The standard ASP.NET designer in Visual Studio 2005/8 is completely usable in this mode of Web Part development. However, debugging is less straight-forward as the .ascx file and the code behind DLL needs to be manually copied to the relevant SharePoint location. However, this is nothing that a simple post build step cannot automate.
I would love to hear other best practices related to web part development that is currently in use.
No comments:
Post a Comment