Sara Chipps
Sara Chipps

Reputation: 9372

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

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

Upvotes: 44

Views: 167278

Answers (5)

Vivek Raj
Vivek Raj

Reputation: 456

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.InnerHtml = "something" + myDiv.InnerText;

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

Upvotes: 5

M4N
M4N

Reputation: 96581

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

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

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

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:

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

Upvotes: 84

Jim Petkus
Jim Petkus

Reputation: 4508

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?

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.

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.

Upvotes: 1

splattne
splattne

Reputation: 104040

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.

Upvotes: 3

Ot&#225;vio D&#233;cio
Ot&#225;vio D&#233;cio

Reputation: 74290

Use asp:Panel for that. It translates into a div.

Upvotes: 15

Related Questions