Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将C#对象呈现为Html_C#_Html_Rendering_Template Engine - Fatal编程技术网

将C#对象呈现为Html

将C#对象呈现为Html,c#,html,rendering,template-engine,C#,Html,Rendering,Template Engine,我们有许多域实体,它们应该被呈现为html格式,在弹出窗口中显示它们的详细信息 我很乐意这样做: Product product = new Product(...); product.ToHtml(); // or: HtmlRenderer.Render(Product); 但我的主要问题是如何从背后做这件事。 我有三个不同的答案: 1。按代码呈现: 我可以简单地编写代码,在ToHtml方法(C#)中呈现Html——问题是它太静态了。如果您想将标题稍微移到中间,您应该更改代码。 此外,在

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

我很乐意这样做:

Product product = new Product(...);
product.ToHtml();  // or: HtmlRenderer.Render(Product);
但我的主要问题是如何从背后做这件事。 我有三个不同的答案:

1。按代码呈现:

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

2。使用XSL:

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

3。使用其他模板引擎:

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

你喜欢什么? 你知道好的发动机吗? 现在我更喜欢第二种解决方案,但速度会很慢


谢谢

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

我真心喜欢方法A。HTML已经是一种标准格式,因此您不应该使用XML(通过XSL-方法2)或自定义格式(方法3)等中间格式太多

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


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

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

编辑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();
输出

<span title="Really">This is just a test!</span>
这只是一个测试!

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

我曾经需要将任何类型的集合呈现到Html表中。我在IEnumerable上创建了一个扩展方法,该方法具有css等的重载。你可以在这里看到我的博客帖子:

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

[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();
}
[System.Runtime.CompilerServices.Extension()]
公共字符串到HTMLTABLE(IEnumerable列表,字符串属性包括descolumns=”“)
{
返回HTMLTable(列表,string.Empty,string.Empty,string.Empty,string.Empty,propertiesToIncludeAsColumns);
}
[System.Runtime.CompilerServices.Extension()]
公共字符串到HTMLTABLE(IEnumerable列表、字符串表样式、字符串标题样式、字符串行样式、字符串替换样式、字符串属性包括子列=)
{
动态结果=新建StringBuilder();
if(String.IsNullOrEmpty(tablestyle)){
结果。追加(“”);
}否则{
result.Append((Convert.ToString(“”);
}
DynamicPropertyArray=typeof(T).GetProperties();
foreach(propertyArray中的对象属性){
如果(string.IsNullOrEmpty(propertiesToIncludeAsColumns)| | propertiesToIncludeAsColumns.Contains(prop.Name+“,”)包含{
if(String.IsNullOrEmpty(headerStyle)){
AppendFormat(“{0}”,prop.Name);
}否则{
AppendFormat(“{1}”,headerStyle,prop.Name);
}
}
}

对于(inti=0;i个人而言,我将结合方法二和方法三:只需使用反射创建一个通用XML文档,比如:

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

...

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

我非常同意John Feminella的观点。将HTML呈现直接集成到域实体中是对域的一种可怕的污染,带有完全任意的外部顾虑。正如John所说,这样做会使实体变得非常脆弱,并破坏两者这些关键规则包括:关注点分离和单一责任

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


在您的演示/视图中,保持渲染在它所属的位置,不要用更高级别的关注点污染您的域。

经过一点研究,我制作了自己的函数,将任何对象转换为HTMLSTRING

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()
将公共函数ToHtmlString(ByVal fObj作为对象)作为字符串
Dim pType=fObj.GetType()
Dim props As IList(Of PropertyInfo)=pType.GetProperties()
作为对象的Dim值=无
Dim htmlString As String=“”
对于道具中的每个p
value=p.GetValue(fObj,无)
如果