在C#中生成HTML页面-最佳做法 [英] Generating HTML page in C# - Best practices

查看:262
本文介绍了在C#中生成HTML页面-最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在我的C#代码中生成一个大的html页面(这不是一个网站,只是一个大的单页html报告)

I have to generate a big html page in my C# code (It's not a site, just a big single-page html report)

页面包含在一个页面中编译的不同部分.每个部分均包含CSS样式,与之相关的javascript部分和正文. CSS样式是静态部分,脚本&身体部位是使用不同的输入数据(CSV文本)生成的.

Page contains a different sections compiled in one page. Each section contains CSS styles, javascript parts and body related to it. CSS style are static parts, script & body parts are generated using a different input data (csv text).

我第一个简化多代生成的无用的解决方案是创建一个构建器函数:

My first artless solution to simplify all-in-one generation is to create a builder function:

 private static string BuildHtmlPage(string[] cssParts, string[] scriptParts, string[] bodyParts)
    {
        var htmlPage = "";
        htmlPage += @"<!DOCTYPE HTML>
 <html>";

htmlPage += "\n<head>";

        htmlPage += "\n<style>\n";
            foreach (var cssPart in cssParts)
            {
                htmlPage += cssPart +"\n";
            }
        htmlPage += "</style>\n";

        htmlPage += @"<script type=""text/javascript"">";
        htmlPage += "window.onload = function() {";

            foreach (var scriptPart in scriptParts)
            {
                htmlPage += scriptPart + "\n";
            }

        htmlPage += @"}
</script>";

htmlPage += "\n</head>";

        htmlPage += "\n<body>\n";
            foreach (var bodyPart in bodyParts)
            {
                htmlPage += bodyPart + "\n";
            }
        htmlPage += "\n</body>";

htmlPage += "\n</html>";

return htmlPage;

    }

然后生成一个小" html部分,并像这样使用它:

Then to generate a "small" html parts and use it like this:

var htmlResult = BuildHtmlPage(
            new [] {style1, style2 },
            new [] {script1, script2, script3 },
            new [] {body1, body2, body3 }
        );

这使我的代码更简洁一些,但由于将许多html代码混入C#代码中,因此它看起来仍然很丑陋且难以维护.

It made my code a little cleaner, but it still looks ugly and hard maintainable because of a lot of html code mixed into C# code.

您可以建议什么样的想法来处理此类任务?首先,我的意思是将HTML代码与C#分开.

What ideas to handle such task could you suggest? First, I mean separation of html code from C#.

推荐答案

这里是一种非常干净的方法,它将使您能够从Web应用程序中获得所有功能,HTML的Visual Studio格式,Razor(基本上是MVC项目):

Here is a very clean approach which will empower you with all the functionality you get from a web application, Visual Studio formatting of HTML, Razor (basically everything within an MVC project):

  1. 创建一个ASP.NET MVC项目.
  2. 创建视图就像创建MVC视图一样.
  3. 一旦您对外观感到满意,然后创建另一个应用程序(控制台,Windows窗体等)并从中引用MVC应用程序.
  4. 控制台应用程序可以从MVC应用程序获取视图,而不是使用浏览器.

此后,我将假设我们有一个将使用MVC应用程序的控制台应用程序.

Hereinafter, I am going to assume we have a console application which will use the MVC application.

配置MVC应用程序的步骤

这些步骤将预编译您的视图.因此,稍后我们将能够直接从控制台应用程序访问视图.

These steps will pre-compile your views. Thus later we will be able to access the views directly from the console application.

  1. 右键单击您的MVC项目,然后添加以下NuGet软件包:
  1. Right click your MVC project and add these NuGet packages:
  1. RazorGenerator.MsBuild
  2. RazorGenerator.Mvc
  1. RazorGenerator.MsBuild
  2. RazorGenerator.Mvc

  • 在记事本中打开MVC项目的.csproj文件并添加以下元素:

  • Open your MVC project's .csproj file in notepad and add these elements:

    1.在最顶部的PropertyGroup元素中添加<MvcBuildViews>true</MvcBuildViews>

    1.In the topmost PropertyGroup element, add <MvcBuildViews>true</MvcBuildViews>

    2.在文件的末尾添加:

    2.At the very end of the file add:

    <Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
        <AspNetCompiler VirtualPath="temp" PhysicalPath="$(WebProjectOutputDir)" />
    </Target>
    

    3.构建项目.我们需要确保视图已编译.为了确保它实际上已经被编译,请在.cshtml文件中编写一些未编译的代码.编译时,如果一切都已正确设置,则编译应会失败,表明编译器也在编译视图.如果没有失败,则上述步骤之一未按指定完成.如果失败,那就是好消息.消除错误,然后重新编译.

    3.Build the project. We need to make sure the views are compiled. To make sure it is actually being compiled, in the .cshtml file write some code that does not compile. When you compile, if everything has been setup properly, the compilation should fail indicating that the compiler is compiling the views also. If it does not fail, then one of the above steps was not done as specified. If it fails, good news. Remove the error and compile again.

    配置控制台应用程序的步骤

    1. 右键单击该项目,然后添加 RazorGenerator.Testing .即使我们没有进行测试,我们仍将使用该库来生成视图的HTML.
    2. 添加对MVC应用程序的引用,就像引用DLL一样.
    3. 右键单击MVC项目参考,然后从上下文菜单中选择View in Object Browser.您的视图将位于ASP命名空间中.请记下视图的名称.
    4. 创建视图的实例,如下面的用法所示,您已完成.例如,我的视图的名称为_Views_Test_Index_cshtml.
    1. Right click the project and add the RazorGenerator.Testing. Even though we are not testing, we will use this library to generate the HTML of the views.
    2. Add a reference to the MVC application as if you were referencing a DLL.
    3. Right click the MVC project reference and select View in Object Browser from context menu. Your views will be within the ASP namespace. Please note the name of the view.
    4. Create an instance of your view as shown in Usage below and you are done. For example, my view's name was _Views_Test_Index_cshtml.

    如您所见,以上大多数步骤仅是设置步骤.

    As you can see most of the above steps are just setup.

    用法

    我做了一个快速测试,这就是我需要的所有代码:

    I did a quick test and this was all the code I needed:

    var view = new ASP._Views_Test_Index_cshtml();
    view.ViewBag.Model = new List<string>() { "One", "Two", "Three" };
    var html = view.RenderAsHtml();
    

    由于View.Model是只读的,因此我使用ViewBag.Model设置视图的模型.这是视图:

    Since the View.Model is readonly, I used ViewBag.Model to set the model for the view. And here is the view:

    @{
        ViewBag.Title = "Index";
        var MyModel = this.ViewBag.Model as List<string>;
    }
    
    @for (int i = 0; i < MyModel.Count ; i++)
    {
        <label>@MyModel[i]</label>
    }
    

    这是生成的HTML:

    <label>One</label>
    <label>Two</label>
    <label>Three</label>
    

    您可以将ViewBag中所需的任何内容传递给视图.您可能会找到本文有用.

    You can pass whatever you need in ViewBag to your view. You may find this article helpful.

    这篇关于在C#中生成HTML页面-最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆