I have some html that is going to be in every page so i stuck it in a .cs file. This piece of html has a lot of quotes so i would prefer not to escape each of the (\"). It isnt hard to since i can use find/replace but i wanted to know. Is there a nice way to mix html and CS so i can easily generate the page?
If you use @string literals you can escape double quotes with 2 double quotes. Slightly more readable (but not much)...
For the specific case of double quote, there's not a much better way. Generally, you can use verbatim strings. They will handle line breaks and all escape characters except "
which should be replaced with ""
:
Response.Write(@"<html>
<body>
<h1 style=""style1"">Hello world</h1>
</body>
</html>");
You could do this with single quotes:
string MyHTML = @"<html>
<body>
<div class='foo'>...</div>
</body>
</html>";
or do double double quotes:
string MyHTML = @"<html>
<body>
<div class=""foo"">...</div>
</body>
</html>";
You can use the @ to treat it literally, or you can take a look at the HtmlTextWriter class for a more programmatic approach.
You can use the legacy include directives in asp.net
You can then have your block of HTML in a separate .html file.
<!-- #include PathType = FileName -->
Rather than having your HTML in C# code move it to resource file. Here's how (for Visual Studio 2008):
- Right-click on the project, select "Add New Item..."
- Select Resource File. Leave Resource.resx as file name. A prompt will appear - select yes to place file in App_GlobalResources folder.
- Double-click Resource.resx. Add new string item MyHtml.
In your code, use Resources.Resource.MyHtml:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Resources.Resource.MyHtml);
}
See also: How to: Create Resource Files for ASP.NET Web Sites
Why wouldn't you just stick that HTML into a user control and then just add that user control to all the pages that use that HTML?
You say same html on EVERY page. Have you considered using a master page with a content placeholder for your common content? You could combine this with the user control idea mentioned by King Avitus.