3

How could I make a code that when I click a button on asp.net, an alert message of bootstrap or message box appears?

protected void ButtonLogin_Click(object sender, EventArgs e)
    {
        //TextBoxEmail.Text = DateTime.Now.ToString();
        string UserName = TextBoxEmail.Text.Trim();
        string password = TextBoxPassword.Text.Trim();
        OracleConnection conn = new OracleConnection(strConnString);
        conn.Open();

        sql = "select password from userlogin where USERNAME = '" + UserName + "' and password ='" + password + "' ";
    cmd = new OracleCommand(sql, conn);


    // orada=new OracleDataAdapter(com.CommandText,conn);
    // cmd.CommandType = CommandType.Text;
    dr = cmd.ExecuteReader();
    //dr.Read();

    if (dr.HasRows)
    {
        Label1.Text = "";
        Response.Redirect("Details.aspx");
    }
    else
    {
        Label1.Text = "No data found...";
        conn.Close();
    }

   }

}

Above, in the else portion:

 else
         {
             Label1.Text = "No data found...";
             conn.Close();
         }

When username and password don't match, I want a bootstrap alert or message box to appear on the website: "password is not correct". How could I do that?

4 Answers 4

5

HTML (MasterPage):

<div class="MessagePanelDiv">
    <asp:Panel ID="Message" runat="server" Visible="False">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
        <asp:Label ID="labelMessage" runat="server" />
    </asp:Panel>
</div>

ENUM:

public enum WarningType
{
    Success,
    Info,
    Warning,
    Danger
}

CodeBehind:

/// <summary>
/// Shows a message based of type and message
/// </summary>
/// <param name="message">Message to display</param>
/// <param name="type">ENUM type of the message</param>

public void ShowMessage(string Message, WarningType type)
{
    //gets the controls from the page
    Panel PanelMessage = Master.FindControl("Message") as Panel;
    Label labelMessage = PanelMessage.FindControl("labelMessage") as Label;

    //sets the message and the type of alert, than displays the message
    labelMessage.Text = Message;
    PanelMessage.CssClass = string.Format("alert alert-{0} alert-dismissable", type.ToString().ToLower());
    PanelMessage.Attributes.Add("role", "alert");
    PanelMessage.Visible = true;
}

Usage:

ShowMessage("<strong> Error! </strong> Error message to show", WarningType.Danger);

Edit

CSS Class:

.MessagePanelDiv 
{
    position:fixed;
    left: 35%;
    top:15%;
    width:35%;
}

Javascript timer to auto remove the alert:

$(document).ready(function () {
    window.setTimeout(function () {
        $(".alert").fadeTo(1500, 0).slideUp(500, function () {
            $(this).remove();
        });
    }, 3000);
});

Without MasterPage

 <div class="MessagePanelDiv">
   <asp:Panel ID="Message" runat="server" CssClass="hidepanel">
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    <asp:Label ID="labelMessage" runat="server" />
   </asp:Panel>
 </div>

CSS:

.hidepanel {
   display: none;
 }

CodeBehind:

 labelMessage.Text = "Successfully updated."
 Message.CssClass = String.Format("alert alert-{0} alert-dismissable", Constants.WarningType.Success.ToString().ToLower())
 Message.Attributes.Add("role", "alert")
Sign up to request clarification or add additional context in comments.

2 Comments

and the MessagePanelDiv class?
.MessagePanelDiv { position:fixed; left: 35%; top:15%; width:35%; }
3

For this you need to reference the bootstrap links and jquery

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

Next Add this to your Head Section in Aspx Page:

 <style type="text/css">
        .messagealert {
            width: 100%;
            position: fixed;
             top:0px;
            z-index: 100000;
            padding: 0;
            font-size: 15px;
        }
    </style>
    <script type="text/javascript">
        function ShowMessage(message, messagetype) {
            var cssclass;
            switch (messagetype) {
                case 'Success':
                    cssclass = 'alert-success'
                    break;
                case 'Error':
                    cssclass = 'alert-danger'
                    break;
                case 'Warning':
                    cssclass = 'alert-warning'
                    break;
                default:
                    cssclass = 'alert-info'
            }
            $('#<%=ButtonLogin.ClientID %>').append('<div id="alert_div" style="margin: 0 0.5%; -webkit-box-shadow: 3px 4px 6px #999;" class="alert fade in ' + cssclass + '"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>' + messagetype + '!</strong> <span>' + message + '</span></div>');
        }
    </script>

In Cs Code

  protected void ShowMessage(string Message, MessageType type)
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), System.Guid.NewGuid().ToString(), "ShowMessage('" + Message + "','" + type + "');", true);
    }

Now in else Part call Error function, in succes also you can use this function by changing the Message type

ShowMessage("Aww, password is wrong", MessageType.Error);

3 Comments

Dear Webruster, thanks for your answer. Would you please help me to understand what does this line mean in jquery ' $('#<%=ButtonLogin.ClientID %>'
@ALAMIN in asp.net we shouldnt give the idname directly , when server controls are converted to html they have different id than which you have given so inorder to apply that id, the above mention will get the id after converted to the html form
Thank you very much for your answer. As I am novice I would like to learn this kinds of converting procedure step by step, would you please suggested any link or resource.
3

Old question but for those that just want a simple solution.

You must have a master page with a ContentPlaceHolder with the id of 'main'

Create this class:

public class BootstrapPage : Page
{
    public enum WarningType
    {
        Success,
        Info,
        Warning,
        Danger
    }

    public void ShowNotification(string message, WarningType type)
    {
        var mainContentHolder = Master.FindControl("main") as ContentPlaceHolder;
        Panel notificationPanel = new Panel();
        {
            LiteralControl closeButton = new LiteralControl();
            closeButton.Text = "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>";

            Label notificationMessage = new Label() { Text = message };

            notificationPanel.Controls.Add(closeButton);
            notificationPanel.Controls.Add(notificationMessage);
        }
        notificationPanel.CssClass = string.Format("alert alert-{0} alert-dismissable", type.ToString().ToLower());
        notificationPanel.Attributes.Add("role", "alert");

        mainContentHolder.Controls.AddAt(0, notificationPanel);
    }
}

Then make your WebForm inheirt from BootstrapPage instead of System.Web.UI.Page

Call it whenever needed:

 ShowNotification("Error: You can't do that!", WarningType.Error);

1 Comment

I really appreciate your piece of code and it works pefectly. but i have couple of questions if you don't mind. Does it affect our application by Inheriting Webform from BoostrapPage ? and how to Auto Remove the Alert after few seconds. Please help me here
0

I have been trying to locate a solution which works in C# Web Forms for some time now. I have tried this solution, however I have not been successful. I have been using a simple Web Application, where I have not been able to get alerts to show on an action.

Now I have found a somewhat functioning solution, however not ideal, using bootstrap.

Front end code for content2

div id="liveAlertPlaceholder"></div>             
                <asp:Button id="liveAlertBtn" class="btn btn-primary" runat="server" Text="Live alert button" OnClick="liveAlertBtn_Click"/>

Front end code for content 1 & script

<script>
    function triggerAlertFunction() {
        const alertPlaceholder = document.getElementById('liveAlertPlaceholder');
        const wrapper = document.createElement('div');
        wrapper.innerHTML = [
            `<div class="alert alert-primary" role="alert">`,
            `  A simple primary alert—check it out! `,
            '  </div>',               
        ].join('')
        alertPlaceholder.append(wrapper);
                  
    }
    </script>

In backend c# aspx.cs

protected void liveAlertBtn_Click(object sender, EventArgs e)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "triggerAlertFunction()", true);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.