在webforms开发过程中可以将服务端控件直接转html,来实现类似模板引擎的效果:

下面是实现代码:

.aspx部分

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ControlToHtml.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Literal ID="literal" runat="server" />
        </div>
    </form>
</body>
</html>

.cs部分

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ControlToHtml
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!this.IsPostBack)
            {
                Button btn=new Button();

                btn.Text = "按钮";
                string html=RenderControlToHtml(btn);
                literal.Text=html;
            }
        }
     
        public string RenderControlToHtml(Control ControlToRender)
        {
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder);
            System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
            ControlToRender.RenderControl(htmlWriter);
            return stringBuilder.ToString();
        }
    }
}