将 C# 对象呈现为 Html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/908181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:34:27  来源:igfitidea点击:

Rendering C# Objects to Html

c#htmlrenderingtemplate-engine

提问by rabashani

We have bunch of Domain Entities which should be rendered to an html format, which shows their detail in a pop up window.

我们有一堆域实体,它们应该呈现为 html 格式,在弹出窗口中显示它们的详细信息。

I would be glad to do something like this:

我很乐意做这样的事情:

Product product = new Product(...);
product.ToHtml();  // or: HtmlRenderer.Render(Product);

but my main problem is how to do this stuff from behind. I have 3 different answers:

但我的主要问题是如何从后面做这些事情。我有3个不同的答案:

1. Render By Code:

1.按代码渲染:

I can simply write my code for rendering the Html inside the ToHtml Method (C#) - the problem it is that it is toostatic. if you would like to move a little bit the header to the middle you should change code. moreover, it is very hard to read Html indentation in C#.

我可以简单地编写用于在 ToHtml 方法(C#)中呈现 Html 的代码 - 问题在于它静态了。如果您想将标题稍微移动到中间,您应该更改代码。此外,在 C# 中阅读 Html 缩进非常困难。

2. Using XSL:

2. 使用 XSL:

XSL Files can easily manage the Html template and using XSLT I can transform XML file to the right place of the documents. the parser already written by someone else (just need to learn the syntax) ** for this we will need that each object could serialize to Xml. and if the object changed -> the Xml will be changed --> the xslt need to be changed too ** this will also give me the option to indent the html easily for example: adding css capabilities and\or change the html design

XSL Files 可以轻松管理 Html 模板,使用 XSLT 我可以将 XML 文件转换到文档的正确位置。其他人已经编写的解析器(只需要学习语法)** 为此,我们需要每个对象都可以序列化为 Xml。如果对象更改 -> Xml 将更改 -> xslt 也需要更改 ** 这也将使我可以轻松缩进 html,例如:添加 css 功能和\或更改 html 设计

3. using other template engine:

3.使用其他模板引擎:

Write my own C# -> Html template Engine so it will read the template from file (*.template) and will insert the right property in the right place of the template using reflection. ** in this solution we have many issues that we can think of, for example: how the syntax should be like? is this thing ok? %Name% %Description% and how we can handle arrays? ** maybe we can use an existing engine (Brail or T4-Templating)?

编写我自己的 C# -> Html 模板引擎,以便它将从文件 (*.template) 中读取模板,并使用反射将正确的属性插入模板的正确位置。** 在这个解决方案中,我们有很多我们可以想到的问题,例如:语法应该是怎样的?这东西好吗? %Name%%Description% 以及我们如何处理数组?** 也许我们可以使用现有引擎(Brail 或 T4-Templating)?

What do you prefer? do you know a good engine? for now I prefer the second solution, but it gonna be very slow.

你喜欢哪个?你知道好的发动机吗?现在我更喜欢第二种解决方案,但它会很慢。

thanks

谢谢

采纳答案by jrista

I can't agree more with John Feminella. Integrating Html rendering directly into your domain entities is a horrid pollution of your domain with a completely arbitrary and external concern. Like John said, you will make your entities very brittle by doing that, and break both of those critical rules: Separation of Concerns and Single Responsibility.

我完全同意约翰费米内拉的观点。将 Html 渲染直接集成到域实体中是对域的可怕污染,具有完全任意和外部的关注。就像约翰所说的那样,这样做会使您的实体变得非常脆弱,并打破这两个关键规则:关注点分离和单一职责。

From the choices you gave, #3 is the closest to an appropriate way to do it. You need not write your own template engine. There are plenty free and ready-made template engines on the net that will do the job more than adequately (NVelocity, StringTemplate, Brail, etc. etc.)

从你给出的选择来看,#3 是最接近合适的方法。您无需编写自己的模板引擎。网上有很多免费和现成的模板引擎可以胜任这项工作(NVelocity、StringTemplate、Brail 等)

Keep rendering where it belongs...in your presentation/view, and don't pollute your domain with higher level concerns.

继续在它所属的地方渲染......在您的演示文稿/视图中,不要用更高级别的问题来污染您的域。

回答by John Feminella

This is the job of your view, not your controllers or models. As you suspect, using method (1) will make your changes very brittle. Instead, write a view fragment for each way in which you'd like to render a particular domain entity. Then simply pull in the appropriate views to build your final page.

这是您的视图的工作,而不是您的控制器或模型。正如您所怀疑的那样,使用方法 (1) 会使您的更改变得非常脆弱。相反,为您希望呈现特定域实体的每种方式编写一个视图片段。然后简单地拉入适当的视图来构建您的最终页面。

回答by Andrei R?nea

I sincerely prefer method A. The HTML is already a standard so you shouldn't beat yourself up too much with intermediary formats such as XML (via XSL - method 2) or a custom format (method 3).

我真诚地更喜欢方法 A。HTML 已经是一个标准,所以你不应该用诸如 XML(通过 XSL - 方法 2)或自定义格式(方法 3)之类的中间格式来打击自己。

If writing in/for ASP.NET MVC you could however build an .ASCX (user control) that would accept an object of your type and render the appropiate HTML. And you don't get the nasty C# indentation and no highlighting nor autocomplete.

如果在/为 ASP.NET MVC 编写,您可以构建一个 .ASCX(用户控件),它会接受您的类型的对象并呈现适当的 HTML。而且您不会得到讨厌的 C# 缩进,也不会突出显示或自动完成。

You could also write multiple User views to accomodate different scenarios for one object type.

您还可以编写多个用户视图来适应一种对象类型的不同场景。

回答by benjamin

Is there a reason you do not want to create a custom control .ascx file that takes domain entities object as an argument and then you can make the gui any way you want. This way you could dynamically add the controls to the page and just set a property to populate them.

您是否有理由不想创建将域实体对象作为参数的自定义控件 .ascx 文件,然后您可以以任何方式制作 gui。通过这种方式,您可以将控件动态添加到页面,然后只需设置一个属性来填充它们。

Edit 1:Just render the control to an HTMLTextWriter instead of placing it on the page.

编辑 1:只需将控件呈现给 HTMLTextWriter 而不是将其放置在页面上。

        StringBuilder outString = new StringBuilder();
        StringWriter outWriter = new StringWriter(outString);
        HtmlTextWriter htmlText = new HtmlTextWriter(outWriter);
        System.Web.UI.WebControls.Label lbl1 = new System.Web.UI.WebControls.Label();
        lbl1.Text = "This is just a test!";
        lbl1.ToolTip = "Really";
        lbl1.RenderControl(htmlText);
        ViewData["Output"] = outString.ToString();

Output

输出

<span title="Really">This is just a test!</span>

Of course use your custom control instead of a built in control but this was a quick and easy demo.

当然,使用您的自定义控件而不是内置控件,但这是一个快速而简单的演示。

回答by BFree

I once had a need to render a collection of any type to an Html Table. I created an extension method on IEnumerable<T> that had overloads for css and the like. You can see my blog post about it here:

我曾经需要将任何类型的集合渲染到 Html 表。我在 IEnumerable<T> 上创建了一个扩展方法,它具有 css 等的重载。你可以在这里看到我的博客文章:

http://crazorsharp.blogspot.com/2009/03/cool-ienumberable-extension-method_25.html

http://crazorsharp.blogspot.com/2009/03/cool-ienumberable-extension-method_25.html

It uses reflection to get all the properties of the object, and renders a nice little table. See if that would work for you.

它使用反射来获取对象的所有属性,并呈现一个漂亮的小表格。看看这是否适合你。

[System.Runtime.CompilerServices.Extension()]
public string ToHtmlTable<T>(IEnumerable<T> list, string propertiesToIncludeAsColumns = "")
{
    return ToHtmlTable(list, string.Empty, string.Empty, string.Empty, string.Empty, propertiesToIncludeAsColumns);
}

[System.Runtime.CompilerServices.Extension()]
public string ToHtmlTable<T>(IEnumerable<T> list, string tableSyle, string headerStyle, string rowStyle, string alternateRowStyle, string propertiesToIncludeAsColumns = "")
{
    dynamic result = new StringBuilder();
    if (String.IsNullOrEmpty(tableSyle)) {
        result.Append("<table id=\"" + typeof(T).Name + "Table\">");
    } else {
        result.Append((Convert.ToString("<table id=\"" + typeof(T).Name + "Table\" class=\"") + tableSyle) + "\">");
    }

    dynamic propertyArray = typeof(T).GetProperties();

    foreach (object prop in propertyArray) {
       if (string.IsNullOrEmpty(propertiesToIncludeAsColumns) || propertiesToIncludeAsColumns.Contains(prop.Name + ",")) {
        if (String.IsNullOrEmpty(headerStyle)) {
            result.AppendFormat("<th>{0}</th>", prop.Name);
        } else {
            result.AppendFormat("<th class=\"{0}\">{1}</th>", headerStyle, prop.Name);
        }
      }
    }

    for (int i = 0; i <= list.Count() - 1; i++) {
        if (!String.IsNullOrEmpty(rowStyle) && !String.IsNullOrEmpty(alternateRowStyle)) {
            result.AppendFormat("<tr class=\"{0}\">", i % 2 == 0 ? rowStyle : alternateRowStyle);

        } else {
            result.AppendFormat("<tr>");
        }
        foreach (object prop in propertyArray) {
            if (string.IsNullOrEmpty(propertiesToIncludeAsColumns) || propertiesToIncludeAsColumns.Contains(prop.Name + ",")) {
                object value = prop.GetValue(list.ElementAt(i), null);
                result.AppendFormat("<td>{0}</td>", value ?? String.Empty);
            }
        }
        result.AppendLine("</tr>");
    }

    result.Append("</table>");

    return result.ToString();
}

回答by MartinStettner

Personally, I'd combine method two and three: Just create a generic XML document using reflection, say:

就个人而言,我会结合方法二和方法三:只需使用反射创建一个通用的 XML 文档,例如:

<object type="xxxx">
    <property name="ttt" value="vvv"/>
    ...
</object>

and use an XSTL stylesheet to create the actual HTML from this.

并使用 XSTL 样式表从中创建实际的 HTML。

回答by Syed Shariq

After bit of research i made my own function to convert Any Object toHtmlString.

经过一番研究,我制作了自己的函数来将任何对象转换为 HtmlString。

VB .Net Code:

VB .Net 代码:

 Public Function ToHtmlString(ByVal fObj As Object) As String
    Dim pType = fObj.GetType()
    Dim props As IList(Of PropertyInfo) = pType.GetProperties()
    Dim value As Object = Nothing
    Dim htmlString As String = "<html><body><form>"

    For Each p In props
        value = p.GetValue(fObj, Nothing)
        If value <> Nothing Then
            htmlString += String.Format("<input type=""hidden"" name=""{0}"" id=""{0}"" value=""{1}""/>", p.Name, value)
        End If
    Next

    htmlString += "</form></body></html>"
    Return htmlString.ToString()

it will get the property name and value from a particular object. you can manipulate html based on your

它将从特定对象获取属性名称和值。你可以根据你的