tags:

views:

260

answers:

8

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?

A: 

If you use @string literals you can escape double quotes with 2 double quotes. Slightly more readable (but not much)...

Arnshea
+4  A: 

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>");
Mehrdad Afshari
+1  A: 

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>";
Colin Burnett
A: 

You can use the @ to treat it literally, or you can take a look at the HtmlTextWriter class for a more programmatic approach.

Brandon
+2  A: 

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 -->
Keith
+8  A: 

Rather than having your HTML in C# code move it to resource file. Here's how (for Visual Studio 2008):

  1. Right-click on the project, select "Add New Item..."
  2. Select Resource File. Leave Resource.resx as file name. A prompt will appear - select yes to place file in App_GlobalResources folder.
  3. 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

Pavel Chuchuva
+1, solved the underlying problem
Iceman
Makes perfect sense when you want to output full HTML but for situations like page generation in ASP.NET MVC (where your page is just a patchy substitution of values), it's far from ideal to have each small piece of HTML in resource file.
Mehrdad Afshari
+3  A: 

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?

Avitus
+3  A: 

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.

Paul