user34537
user34537

Reputation:

mixing html and C#

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?

Upvotes: 0

Views: 2692

Answers (8)

user120998
user120998

Reputation:

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.

Upvotes: 3

Avitus
Avitus

Reputation: 15968

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?

Upvotes: 3

Pavel Chuchuva
Pavel Chuchuva

Reputation: 22475

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

Upvotes: 8

Keith
Keith

Reputation: 155872

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 -->

Upvotes: 2

Brandon
Brandon

Reputation: 70032

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

Upvotes: 0

Colin Burnett
Colin Burnett

Reputation: 11548

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>";

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422252

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>");

Upvotes: 4

Shea
Shea

Reputation: 11243

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

Upvotes: 0

Related Questions