在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();
        }
    }
}



如果您对C#游戏开发感兴趣,可以扫下面二维码加入我们的QQ群来一起学习交流

原创文章,转载请注明本文链接地址(违者必究):ASP.NET WebForms WebControl转html