tags:

views:

3139

answers:

12
+1  Q: 

Write html in C#

I have code like this. Is there a way to make it easier to write and maintain? Using C# .NET 3.5

string header(string title)
{
    StringWriter s = new StringWriter();
    s.WriteLine("{0}","<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"&gt;");
    s.WriteLine("{0}", "<html>");
    s.WriteLine("<title>{0}</title>", title);
    s.WriteLine("{0}","<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
    s.WriteLine("{0}", "</head>");
    s.WriteLine("{0}", "<body>");
    s.WriteLine("{0}", "");
}

-edit- i didnt know it then but i could write

s.WriteLine("{0}", @"blah blah

many
new
lines
blah UHY#$&_#$_*@Y KSDSD<>\t\t\t\t\t\tt\t\t\\\t\t\t\t\\\h\th'\h't\th
hi
done"); 

and it will work but need to replace all " with ""

+15  A: 

You're probably better off using an HtmlTextWriter or an XMLWriter than a plain StringWriter. They will take care of escaping for you, as well as making sure the document is well-formed.

This page shows the basics of using the HtmlTextWriter class.

lc
+14  A: 

When I deal with this problem in other languages I go for a separation of code and HTML. Something like:

1.) Create a HTML template. use [varname] placeholders to mark replaced/inserted content.
2.) Fill your template variables from an array or structure/mapping/dictionary

Write( FillTemplate(myHTMLTemplate, myVariables) ) # pseudo-code
SpliFF
can i get a link to an example of how to make a HTML template? in whatever language? (i can deal with non C# is its .NET)
acidzombie24
There are existing template engines that may help make this easier. See wikipedia for a list: http://en.wikipedia.org/wiki/Template_engine_(web)
iammichael
The Parser class in here is simple/easy to use: http://www.codeproject.com/KB/dotnet/mailtemplates.aspx
russau
+3  A: 
return string.Format(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN""      ""http://www.w3.org/TR/html4/strict.dtd""&gt;
<html>
<title>{0}</title>
<link rel=""stylesheet"" type=""text/css"" href=""style.css"">
</head>
<body>
", title);
Jimmy
Depending on where title came from, you probably want to HTML-encode title before blindly inserting it into a string.
Jacob
would that keep newlines?
acidzombie24
+1  A: 

You can use ASP.NET to generate your HTML outside the context of web pages. Here's an article that shows how it can be done.

Jacob
It could be used to generate an HTML email or something else that isn't a website. Also, this isn't an answer.
llamaoo7
You can use ASP.NET to output HTML outside the context of a web site.
Jacob
I wouldnt go as far as downvoting this, as its a valid question, but it shoud have been a comment to the OP instead of an aswer
Neil N
Jacob is correct... you can use the ASP.NET rendering engine... though there is obviously more to it than just saying you can use it.
Bryan Sebastian
i didnt up or down vote this but how would i use the rendering engine? link to a page of any example would be fine.
acidzombie24
+3  A: 

The most straight forward way is to use an XmlWriter object. This can be used to produce valid HTML and will take care of all of the nasty escape sequences for you.

JaredPar
A: 

You could write your own classes with its Render method, and another attributes, to avoid a great mess if you use it a lot, and then use the HTMLWriter or the xmlwriter as well. This logic is used in the asp.net pages, you can inherit from webControl and override the render method, wich is great if you are developing server-side controls.
This could be a good example.

Regards

Matias
A: 

It really depends what you are going for, and specifically, what kind of performance you really need to offer.

I've seen admirable solutions for strongly-typed HTML development (complete control models, be it ASP.NET Web Controls, or similar to it) that just add amazing complexity to a project. In other situations, it is perfect.

In order of preference in the C# world,

  • ASP.NET Web Controls
  • ASP.NET primitives and HTML controls
  • XmlWriter and/or HtmlWriter
  • If doing Silverlight development with HTML interoperability, consider something strongly typed like link text
  • StringBuilder and other super primitives
Jeff Wilcox
+1  A: 

You could use System.Xml.Linq objects. They were totally redesigned from the old System.Xml days which made constructing XML from scratch a nut-searing pain.

Other than the doctype I guess, you could easily do something like:

var html = new XElement("html",
    new XElement("head",
        new XElement("title", "My Page")
    ),
    new XElement("body",
        "this is some text"
    )
);
Josh Einstein
+5  A: 

I know you asked about C#, but if you're willing to use any .Net language then I highly recommend Visual Basic for this exact problem. Visual Basic has a feature called XML Literals that will allow you to write code like this.

Module Module1

    Sub Main()

        Dim myTitle = "Hello HTML"
        Dim myHTML = <html>
                         <head>
                             <title><%= myTitle %></title>
                         </head>
                         <body>
                             <h1>Welcome</h1>
                             <table>
                                 <tr><th>ID</th><th>Name</th></tr>
                                 <tr><td>1</td><td>CouldBeAVariable</td></tr>
                             </table>
                         </body>
                     </html>

        Console.WriteLine(myHTML)
    End Sub

End Module

This allows you to write straight HTML with expression holes in the old ASP style and makes your code super readable. Unfortunately this feature is not in C#, but you could write a single module in VB and add it as a reference to your C# project.

Writing in Visual Studio also allows proper indentation for most XML Literals and expression wholes. Indentation for the expression holes is better in VS2010.

Jim Wallace
I totally forgot about that. Good call.
Josh Einstein
I never write anything that has to do with XML or HTML in C# anymore. VB is just a great language for interfacing with web SOAP/REST Apis
Jim Wallace
+2  A: 

If you're looking to create an HTML document similar to how you would create an XML document in C#, you could try Microsoft's open source library, the Html Agility Pack.

It provides an HtmlDocument object that has a very similar API to the System.Xml.XmlDocument class.

Dan Herbert
Html Agility Pack was not written by Microsoft.
Mauricio Scheffer
It probably wasn't officially sponsored by Microsoft, but at the very least it was written by a Microsoft employee, or at least someone with an @microsoft.com email address...
Dan Herbert
Yup, it was written by Simon Mourier who at that time was working at Microsoft... I wouldn't call it "Microsoft's open source library" though.
Mauricio Scheffer
A: 

This is not a generic solution, however, if your pupose is to have or maintain email templates then System.Web has a built-in class called MailDefinition. This class is used by the ASP.NET membership controls to create HTML emails.

Does the same kind of 'string replace' things as mentioned above, but packs it all into a MailMessage for you.

Here is an example from MSDN:

ListDictionary replacements = new ListDictionary();
replacements.Add("<%To%>",sourceTo.Text);
replacements.Add("<%From%>", md.From);
System.Net.Mail.MailMessage fileMsg;
fileMsg = md.CreateMailMessage(toAddresses, replacements, emailTemplate, this); 
return fileMsg;
Brendan Kowitz
A: 

You could use some third party open-source libraries to generated strong typed verified (X)HTML, such as CityLizard Framework or Sharp DOM.

Serge Shandar