从后面的代码中添加.aspx中的新标记

时间:2013-09-05 16:08:11

标签: asp.net

我正在尝试在运行时在现有的.aspx页面中添加一些额外的文本。但没有找到任何合适的方法来做到这一点。

有没有办法在运行时从代码中追加新标记到.aspx页面?

例如:

我在.aspx页面中有这个 -

<html>
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">

我想从代码中追加这个 -

    <div>
    hghjggjg
    </div>
    </form>
</body>
</html>

谢谢。

3 个答案:

答案 0 :(得分:1)

...动态 ..aspx

<%@ Control Language="C#" AutoEventWireup="true"     CodeBehind="xx.ascx.cs"   Inherits="xx.layouts.xxSublayout" %>
<%@ Register Assembly="System.Web" Namespace="System.Web.UI" TagPrefix="asp" %>
<asp:LiteralControl runat="server" ID="openingTag" />
<asp:PlaceHolder runat="server" id="contentPanel" />
<asp:LiteralControl runat="server" ID="closingTag" />

代码隐藏..添加带有文本的div到除PAGE_LOAD之外的某些方法...

 var inputWrapper = new HtmlGenericControl("div"){ID = "d1"};
        inputWrapper.Attributes.Add("class", "yourcssclass");
        inputWrapper.InnerText = "hghjggjg";
        contentPanel.Controls.Add(inputWrapper);

持久标记回发...

            //add div ID to list, add list to session so it can be recreated on the page_INIT, this must be done or btn will NOT exist when "Get vCard" is clicked.
            PostbackIDs.Add(inputWrapper.ID);
            Session["pb"] = PostbackIDs;

on INit ...

//Must recreate controls from session, so label is existing
       if (Session["pb"] != null)
        {
            var pblist = (List<string>)Session["pb"];
            foreach (var id in pblist)
            {                   
                // label
                var inputWrapper= new HtmlGenericControl("div") { ID = id };
                inputWrapper.Attributes.Add("class", "yourcssclass");                    
                contentPanel.Controls.Add(inputWrapper);
            }
        }

由于INIT方法在页面加载之前被点击,因此控件的ID将到位以向其添加文本。

答案 1 :(得分:0)

在后端创建HTMLElement个实例,用数据填充它们并将它们添加到控件/页面。

答案 2 :(得分:0)

您可以向ASPX添加Label并在运行时修改Text属性。

如果您想在运行时添加控件,PlaceHolder是一个很好的控件来进行调查。但请记住,这些动态声明的控件不会通过PostBack自动保留。

相关问题