简体   繁体   English

混合html和C#

[英]mixing html and C#

I have some html that is going to be in every page so i stuck it in a .cs file. 我在每个页面中都有一些html,所以我将其粘贴在.cs文件中。 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? 这段html有很多引号,所以我宁愿不要转义每个(\\“)。这并不难,因为我可以使用find / replace,但是我想知道。是否有混合html和CS,以便我可以轻松生成页面?

Rather than having your HTML in C# code move it to resource file. 而不是用C#代码将HTML移到资源文件中。 Here's how (for Visual Studio 2008): 这是(对于Visual Studio 2008):

  1. Right-click on the project, select "Add New Item..." 右键单击项目,选择“添加新项目...”
  2. Select Resource File. 选择资源文件。 Leave Resource.resx as file name. 保留Resource.resx作为文件名。 A prompt will appear - select yes to place file in App_GlobalResources folder. 将出现一个提示-选择“是”将文件放置在App_GlobalResources文件夹中。
  3. Double-click Resource.resx. 双击Resource.resx。 Add new string item MyHtml. 添加新的字符串项目MyHtml。

In your code, use Resources.Resource.MyHtml: 在您的代码中,使用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 另请参见: 如何:为ASP.NET网站创建资源文件

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

您为什么不只是将HTML粘贴到用户控件中,然后仅将该用户控件添加到使用该HTML的所有页面中?

You say same html on EVERY page. 您在每个页面上说相同的html。 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. 您可以将其与King Avitus提到的用户控制思想结合起来。

You can use the legacy include directives in asp.net 您可以在asp.net中使用旧版include伪指令

You can then have your block of HTML in a separate .html file. 然后,您可以将HTML块放在单独的.html文件中。

<!-- #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. 如果使用@string文字,则可以使用2个双引号对双引号进行转义。 Slightly more readable (but not much)... 可读性更高(但不多)...

您可以使用@对其进行字面处理,也可以查看HtmlTextWriter类以获得更多编程方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM