Reputation: 3290
I am in a scenario where i have a bunch of dynamic objects. They are loaded using reflection so there is no way to add code to the view that will be able to generate html to correctly render the object. How should this be done? A Razor helper seems good, but since i dont know the object on compile time, i cant really use these.
What i have done is created a base object called Person and added a virtual method called RenderHTML() in the base class.
public Medic : Person
public Cop : Person
I will then override this RenderHTML method in each class that will generate HTML that will correctly display the additional content that the child classes contain. It works, but it isnt easy to work with. Having to use a single string and add onto it is getting very messy when things get complex.
htmlstring += "some more html";
Is there any way to set some sort of output buffer where i can do something like this.
string html = startBuffer(){
<html>wdfwjewe</html>
}
the content inside the brackets could be plain HTML without anything fancy to escape it and everything will be saved to the html string. I am looking for some kind of syntax highlighting as the current method i have is becoming a pain to work with.
Upvotes: 0
Views: 1822
Reputation: 19158
You can try to use TagBuilder()
This do involve nesting of the tags if you start to build the html from <html>
. Alternative would be StringBuilder()
Example is from documentation
public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
{
// Create tag builder
var builder = new TagBuilder("img");
// Create valid id
builder.GenerateId(id);
// Add attributes
builder.MergeAttribute("src", url);
builder.MergeAttribute("alt", alternateText);
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
// Render tag
return builder.ToString(TagRenderMode.SelfClosing);
}
Upvotes: 1