Tutorial :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?


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


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


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.


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


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


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


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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »