我可以在加载事件时从 C# 的 div 标签中动态添加 HTML 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/467016/
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-04 04:33:25  来源:igfitidea点击:

Can I dynamically add HTML within a div tag from C# on load event?

c#asp.net.net-3.5master-pages

提问by Sara Chipps

Mind you, I am using master pages, but can I locate a div within the page and throw some html in there? Thanks.

请注意,我正在使用母版页,但是我可以在页面中找到一个 div 并将一些 html 放入其中吗?谢谢。

采纳答案by M4N

You can add a div with runat="server" to the page:

您可以在页面中添加一个带有 runat="server" 的 div:

<div runat="server" id="myDiv">
</div>

and then set its InnerHtml property from the code-behind:

然后从代码隐藏设置它的 InnerHtml 属性:

myDiv.InnerHtml = "your html here";

If you want to modify the DIV's contents on the client side, then you can use javascript code similar to this:

如果你想在客户端修改DIV的内容,那么你可以使用类似这样的javascript代码:

<script type="text/javascript">
    Sys.Application.add_load(MyLoad);
    function MyLoad(sender) {
        $get('<%= div.ClientID %>').innerHTML += " - text added on client";
    }
</script>

回答by Otávio Décio

Use asp:Panelfor that. It translates into a div.

asp:Panel为此使用。它转化为一个 div。

回答by splattne

You could reference controls inside the master page this way:

您可以通过以下方式引用母版页内的控件:

void Page_Load()
{
    ContentPlaceHolder cph;
    Literal lit;

    cph = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");

    if (cph != null) {
        lit = (Literal) cph.FindControl("Literal1");
        if (lit != null) {
            lit.Text = "Some <b>HTML</b>";
        }
    }

}

In this example you have to put a Literal control in your ContentPlaceholder.

在此示例中,您必须在 ContentPlaceholder 中放置一个 Literal 控件。

回答by Jim Petkus

You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?

您想将代码放在母版页代码后面,以便将 HTML 插入到使用该母版页的页面的内容中吗?

I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.

我不会通过 FindControl 搜索控件,因为这是一个脆弱的解决方案,如果控件的名称更改,很容易被破坏。

Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.

最好的办法是在母版页中声明一个任何子页都可以处理的事件。该事件可以将 HTML 作为 EventArg 传递。

回答by Vivek Raj

Remember using

记得使用

myDiv.InnerHtml = "something";

will replace all HTML elements in myDIV. you need to append text to avoid that.In that this may help

将替换 myDIV 中的所有 HTML 元素。您需要附加文本以避免这种情况。因为这可能会有所帮助

myDiv.InnerHtml = "something" + myDiv.InnerText;

any html control in myDiv but not ASP html controls(as they are not rendered yet).

myDiv 中的任何 html 控件,但不是 ASP html 控件(因为它们尚未呈现)。