How to insert html code section into a particular place using codebehind on page load
Asked Answered
O

3

5

I have an aspx page where I need to check and display an error message on the page on page_load. The error message is below:

<div class="errorMessage">The user ID or password you entered does not match our records. Please try again. <br /> 
        You may also securely recover your <a href="#">User ID</a> or reset your <a href="#">Password</a> online. 
    </div>

this code block should be added to the page after chechking some conditions...and that part and some other functions are implemented in code behide function page_load()

how do i do this using only the behind the code in page_load() function without writing it inline in the aspx file?

Opalescent answered 9/4, 2012 at 15:19 Comment(0)
G
9

Create a div with an ID and a runat="server":

<div ID="divErrorMessage" runat="server" class="divErrorMessage"></div>

Then from your Page_Load event in the code behind, you can set the inner html of the div:

divErrorMessage.InnerHtml = "Your message";

Setting the flag, runat="server" makes the control available in the code behind

Gaullist answered 9/4, 2012 at 15:29 Comment(0)
U
4

you can just add code like below inthe page_load

protected void Page_Load(object sender, EventArgs e)
{

    Literal lit=new Literal();
    lit.Text = @"<div class='errorMessage'>The user ID or password you entered does not match our records. Please try again. <br /> 
                            You may also securely recover your <a href='#'>User ID</a> or reset your <a href='#'>Password</a> online. 
                        </div>";
    Page.Controls.AddAt(0,lit);

}

In this Example we create a new Literal control and add your HTML in it's Text property, then add this literal control to the controls collection of the current aspx page.

You can change the position of this div by CSS styles, and also you can add it in any existing Panel instead of adding it directly to the "Page.Controls" object, for example you can add it to "Panel1.Controls".

But it's not best practice to do that directly in the code behind, you can better use resource file.

Unrivaled answered 9/4, 2012 at 15:36 Comment(0)
K
0

There are many way to do this, this is one. Wrap your div in an asp Panel control.

<asp:Panel runat="server" ID="pnlErrorMessage">
    <div class="errorMessage">The user ID or password you entered does not match our records. Please try again. <br /> 
    You may also securely recover your <a href="#">User ID</a> or reset your <a href="#">Password</a> online. 
    </div>
</asp:Panel>

in your page_load:

pnlErrorMessage.Visible = true;

Komatik answered 9/4, 2012 at 15:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.