Currently I have a class that represents a document. This document needs to be displayed as HTML. I would like to have a method to call such as GetHTML() that would then call GetHTML() on any properties/sections of the document that needed to be rendered. I was initially thinking about using linq and XElement but am wondering if that may cause issues with certain tags in HTML. Would I better off using an HtmlTextWriter? I am open to any suggestions or best practives for this situation. Thanks!
Currently I have a class that represents a document. This document needs to be
Share
I think you’re talking about having a data Model that can render itself in HTML, and you want to make sure that there is fidelity in the composition and that it can recursively discover and render child objects.
Well, how “classic” ASP.net does this with its rendering model is that everything is a Control, and each control has a Render(HtmlTextWriter) method. Controls that contain child controls (composite controls, user controls, pages, etc) have logic in them to recursively render each of its child controls within the context of itself. E.g. The Render method for a composite controls calls RenderBeginTag, and then it calls RenderChildren and then it calls RenderEndTag, all the while passing around a reference to the same HtmlTextWriter that’s being used to render the entire Response. Things like pages and user controls are even a little more complicated because they also parse templates (aspx), but at the end of the day those templates are just a prescription for a Render method.
Well, the trouble with this is that it sucks from a standpoint of separating concerns. Why does your data document need to contain all the code to render itself in HTML? I also don’t like the idea of GetHtml() because it implies (to me) that you’re going to reinvent something that has already been invented. Reusing an MVC ViewEngine here is probably a good idea: it has lots of features and is easy to develop against compared to something like the HtmlTextWriter.
At any rate. My suggestion would be to create a new interface for your documents classes; let’s call it “iRenderable.” And the single requirement for this interface is a string called “ViewName”.
When you want to convert your document (Model) to HTML, all you do is call RenderPartial(model.ViewName, model). If that document then has iRenderable child elements then (from within that view), you again call RenderPartial(model.SomeChild.ViewName, model.SomeChild).
There you go. MVC does the heavy lifting with the templates and what-not, and you don’t bake a bunch of extra procedural rendering crap into your data model.
You might ask, why bother with the interface if Table knows that it contains Rows? Because there maybe be cases where you have an object (or a collection of objects) that you want to render and your parent view has no knowledge of the type. You would still be able to render the object by attempting to cast to IRenderable.